classSolution { // you need to treat n as an unsigned value publicinthammingWeight(int n) { return Integer.toBinaryString(n).replace("0", "").length(); } }
版本二
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassSolution { // you need to treat n as an unsigned value publicinthammingWeight(int n) { Strings= Integer.toBinaryString(n); intcount=0; for (char ch : s.toCharArray()) { if (ch == '1') { count++; } } return count; } }