Skip to content

Commit b5109bc

Browse files
committed
solve 191: number of 1 bits
1 parent e43e5ae commit b5109bc

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

vscode/191.number-of-1-bits.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
* @lc app=leetcode id=191 lang=java
3+
*
4+
* [191] Number of 1 Bits
5+
*
6+
* https://leetcode.com/problems/number-of-1-bits/description/
7+
*
8+
* algorithms
9+
* Easy (42.02%)
10+
* Total Accepted: 250K
11+
* Total Submissions: 586.7K
12+
* Testcase Example: '00000000000000000000000000001011'
13+
*
14+
* Write a function that takes an unsigned integer and return the number of '1'
15+
* bits it has (also known as the Hamming weight).
16+
*
17+
*
18+
*
19+
* Example 1:
20+
*
21+
*
22+
* Input: 00000000000000000000000000001011
23+
* Output: 3
24+
* Explanation: The input binary string 00000000000000000000000000001011 has a
25+
* total of three '1' bits.
26+
*
27+
*
28+
* Example 2:
29+
*
30+
*
31+
* Input: 00000000000000000000000010000000
32+
* Output: 1
33+
* Explanation: The input binary string 00000000000000000000000010000000 has a
34+
* total of one '1' bit.
35+
*
36+
*
37+
* Example 3:
38+
*
39+
*
40+
* Input: 11111111111111111111111111111101
41+
* Output: 31
42+
* Explanation: The input binary string 11111111111111111111111111111101 has a
43+
* total of thirty one '1' bits.
44+
*
45+
*
46+
*
47+
* Note:
48+
*
49+
*
50+
* Note that in some languages such as Java, there is no unsigned integer type.
51+
* In this case, the input will be given as signed integer type and should not
52+
* affect your implementation, as the internal binary representation of the
53+
* integer is the same whether it is signed or unsigned.
54+
* In Java, the compiler represents the signed integers using 2's complement
55+
* notation. Therefore, in Example 3 above the input represents the signed
56+
* integer -3.
57+
*
58+
*
59+
*
60+
*
61+
* Follow up:
62+
*
63+
* If this function is called many times, how would you optimize it?
64+
*
65+
*/
66+
public class Solution {
67+
// you need to treat n as an unsigned value
68+
public int hammingWeight(int n) {
69+
int count = 0;
70+
while (n != 0) {
71+
n = n & (n - 1);
72+
count++;
73+
}
74+
return count;
75+
}
76+
}
77+

0 commit comments

Comments
 (0)