-
Notifications
You must be signed in to change notification settings - Fork 0
/
Number of 1 Bits
38 lines (36 loc) · 1.5 KB
/
Number of 1 Bits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* Programmer : Dhruv Patel
* Problem Name : Number of 1 Bits
* Used In : Leetcode
* Used As : 191
* Problem :
* Write a function that takes an unsigned integer and returns the number of '1' bits it has
* (also known as the Hamming weight).
* For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011,
* so the function should return 3.
* Credits:
* Special thanks to @ts for adding this problem and creating all test cases.
* Thoughts =>
* Brute Force / Naive Approach :- We convert int number to the BigDecimal with 32-bit string and shooting a loop
* to count ASCII - '49' which returns the number of ones.
*
*/
import java.math.BigDecimal;
class Solution {
public static int hammingWeight(int n) {
BigDecimal b = new BigDecimal(n + "");
StringBuilder b1 = new StringBuilder(String.format("%32s", Integer.toBinaryString(b.intValue()))
.replace(' ', '0'));
int count = 0;
for (char k : b1.toString().toCharArray()) {
if (k == 49) {
count++;
}
}
return count;
}
public static void main(String args[]) {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
System.out.println("Total number of zeroes in number " + i + " " + hammingWeight(i));
}
}
}