class Solution {
public:
int NumberOf1(int n) {
int ans = 1;
int i = 0;
while (n!=0){
if (ans & n){
i++;
}
n >>= 1;
}
return i;
}
};
提交结果:运行超时 运行时间:1001ms 占用内存:0KB 使用语言:C++ 用例通过率:0.00%
//需要考虑负数 题目要求负数用其补码表示
class Solution {
public:
int NumberOf1(int n) {
int count = 0;
if (n < 0){
n = n & 0x7FFFFFFF;
++count;
}
while (n != 0){
count += n & 1;
n = n >> 1;
}
return count;
}
};
提交结果:答案正确 运行时间:3ms 占用内存:500KB 使用语言:C++ 用例通过率:100.00%