前面的题真的都没什么难度啊。。。
这道题使用位运算与,把数据的最后循环统计数据的最后一位是否为1即可。
public int NumberOf1(int n) { int cnt = 0; if ((n & 1) == 1) cnt++; n = n >>> 1; // 如果是负数要提前判断,无符号左移之后变成正数了 while (n > 0) { if ((n & 1) == 1) { cnt++; } n = n >>> 1; } return cnt; }
public int NumberOf1(int n) { int cnt = 0; if ((n & 1) == 1) cnt++; n = n >>> 1; // 如果是负数要提前判断,无符号左移之后变成正数了 while (n > 0) { if ((n & 1) == 1) { cnt++; } n = n >>> 1; } return cnt; }