publicclassSolution {// you need to treat n as an unsigned valuepublicinthammingWeight(int n) { // ๆฏๆฌก้ฝ็ๆๅณ้็ๆฏๅฆ็บ1int count =0;for (int i =0; i <32; i++) { count += n &1; n = n >>1; }return count; }}
optimized
time: O(k), k is the binary length of this num
space: O(1)
publicclassSolution {// you need to treat n as an unsigned valuepublicinthammingWeight(int n) {int count =0;while (n !=0) { count++; n &= (n-1); }return count; }}