We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 5eb61be + e7b67b0 commit 8038a0bCopy full SHA for 8038a0b
1 file changed
LeetCode/count1s.java
@@ -0,0 +1,19 @@
1
+//Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
2
+public class Solution {
3
+ // you need to treat n as an unsigned value
4
+ public int hammingWeight(int n) {
5
+
6
+ int cnt=0;
7
+ int len=0;
8
+ while(len<32)
9
+ {
10
+ if((n&1)==1) //perform bitwise AND and count 1's
11
12
+ cnt++;
13
+ }
14
+ n=n>>1; //right shift digit by one bit
15
+ len++;
16
17
+ return cnt;
18
19
+}
0 commit comments