Skip to content

Commit b2bd14c

Browse files
committed
Added number of bits
1 parent 8c31bc9 commit b2bd14c

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Easy/NumberOfBits.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Write a function that takes an unsigned integer and returns the number of
3+
* ’1' bits it has (also known as the Hamming weight).
4+
*
5+
* For example, the 32-bit integer '11' has binary representation
6+
* 00000000000000000000000000001011, so the function should return 3.
7+
*
8+
* Tags: Bit Manipulation
9+
*/
10+
class NumberOfBits {
11+
public static void main(String[] args) {
12+
NumberOfBits nob = new NumberOfBits();
13+
int n = 111;
14+
System.out.println(nob.hammingWeight(n));
15+
System.out.println(nob.hammingWeightB(n));
16+
System.out.println(nob.hammingWeightC(n));
17+
}
18+
19+
/**
20+
* Pure bit manipulation
21+
* "n &= n - 1" is used to delete the right "1" of n
22+
* Stop when all 1s are deleted and n is zero
23+
*/
24+
public int hammingWeight(int n) {
25+
int res = 0;
26+
while (n != 0) {
27+
res++;
28+
n &= n - 1;
29+
}
30+
return res;
31+
}
32+
33+
/**
34+
* Most straight forward solution
35+
* Iterate 32 times to check each digit in n
36+
*/
37+
public int hammingWeightB(int n) {
38+
int res = 0;
39+
for (int i = 0; i < 32; i++) // no need to iterate 32 times
40+
if ((n >>> i & 0x1) == 1) res++;
41+
return res;
42+
}
43+
44+
/**
45+
* Recursive
46+
* If n is 0 or 1, return n
47+
* If not, return n & 1 + hammingWeightC(n >>> 1)
48+
*/
49+
public int hammingWeightC(int n) {
50+
return n == 0 || n == 1 ? n : (n & 1) + hammingWeightC(n>>>1);
51+
}
52+
}

0 commit comments

Comments
 (0)