Skip to content

Commit 3e1b001

Browse files
committed
feat(leetcode/191): Number of 1 Bits (Easy)
1 parent 0fc6d74 commit 3e1b001

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

โ€Žnumber-of-1-bits/renovizee.java

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,44 @@
22

33
// tag renovizee 3week
44
// 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
66
class Solution {
7-
// Solv1 :
8-
// ์‹œ๊ฐ„๋ณต์žก๋„ : O(n)
9-
// ๊ณต๊ฐ„๋ณต์žก๋„ : O(n)
7+
// Solv2 :
8+
// ์‹œ๊ฐ„๋ณต์žก๋„ : O(1)
9+
// ๊ณต๊ฐ„๋ณต์žก๋„ : O(1)
1010
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;
1118

1219
}
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+
// }
1338
}
1439

1540
//-------------------------------------------------------------------------------------------------------------
1641
// 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
1845
//-------------------------------------------------------------------------------------------------------------

0 commit comments

Comments
ย (0)