你可能以为我会用字符串遍历的方式做,但其实不是。
建议先了解一下如何用位运算判断2的N次幂,然后再看此解:
public int numberOfSetBits(int n) {
int result = 0;
for ( ; n > 0; result++) {
n &= n-1;
}
return result;
}
你可能以为我会用字符串遍历的方式做,但其实不是。
建议先了解一下如何用位运算判断2的N次幂,然后再看此解:
public int numberOfSetBits(int n) {
int result = 0;
for ( ; n > 0; result++) {
n &= n-1;
}
return result;
}
微信扫码登录