File tree Expand file tree Collapse file tree 1 file changed +32
-5
lines changed Expand file tree Collapse file tree 1 file changed +32
-5
lines changed Original file line number Diff line number Diff line change 2
2
3
3
// tag renovizee 3week
4
4
// https://github.com/DaleStudy/leetcode-study/issues/232
5
- // https://leetcode.com/problems/valid-palindrome/ #191 #Easy
5
+ // https://leetcode.com/problems/number-of-1-bits #191 #Easy
6
6
class Solution {
7
- // Solv1 :
8
- // ์๊ฐ๋ณต์ก๋ : O(n )
9
- // ๊ณต๊ฐ๋ณต์ก๋ : O(n )
7
+ // Solv2 :
8
+ // ์๊ฐ๋ณต์ก๋ : O(1 )
9
+ // ๊ณต๊ฐ๋ณต์ก๋ : O(1 )
10
10
public int hammingWeight (int n ) {
11
+ int result = 0 ;
12
+ for (int i = 0 ; i < 32 ; i ++) {
13
+ if (((n >> i ) & 1 ) == 1 ) {
14
+ result ++;
15
+ }
16
+ }
17
+ return result ;
11
18
12
19
}
20
+ // // Solv1 :
21
+ // // ์๊ฐ๋ณต์ก๋ : O(log n)
22
+ // // ๊ณต๊ฐ๋ณต์ก๋ : O(1)
23
+ // public int hammingWeight(int n) {
24
+ // int result = 0;
25
+ // int current = n;
26
+ // while (current >= 2) {
27
+ // if ((current % 2) == 1) {
28
+ // result++;
29
+ // }
30
+ // current = current / 2;
31
+ // }
32
+ // if (current == 1) {
33
+ // result++;
34
+ // }
35
+ // return result;
36
+ //
37
+ // }
13
38
}
14
39
15
40
//-------------------------------------------------------------------------------------------------------------
16
41
// Java ๋ฌธ๋ฒ ํผ๋๋ฐฑ
17
- //
42
+ // 1) String s=Integer.toBinaryString(n); ์ซ์๋ฅผ ์ด์ง์ string์ผ๋ก ๋ณํํ๋ ๋ฐฉ๋ฒ
43
+ // 2) ์ซ์๋ฅผ ๋นํธ ์ฐ์ฐํ๋ ๋ฐฉ๋ฒ n >> i ๋ ์ ์ n์ i ๋งํผ ์ค๋ฅธ์ชฝ์ผ๋ก shift ํจ, ex) 1011 -> 0101
44
+ // 3) & ์ ๋นํธ์์ and ์ฐ์ฐ์ด๊ณ & 1์ ๋ง์ง๋ง ๋นํธ ๊ฒ์ฌ๋ก ํน์ํ๊ฒ ์ฌ์ฉ๋จ, ๋๋ค 1์ธ ๊ฒฝ์ฐ๋ง 1
18
45
//-------------------------------------------------------------------------------------------------------------
You canโt perform that action at this time.
0 commit comments