剑指offer-刷题笔记-简单题-JZ15 二进制中1的个数
版本1是自己写的,比较复杂,将正数和负数分别转换为对应的二进制求得,但是容易理解,版本2比较简洁
版本1
class Solution {
public:
int NumberOf1(int n) {
int flag[32] = {1};
int count = 0;
int temp;
if (n >= 0)
{
while (n != 0)
{
temp = n%2;
if(temp == 1)
{
count ++;
}
n = n/2;
}
}
if (n < 0)
{
n = -n;
int j = 31;
while ((n != 0)&&(j>=0))
{
temp = n%2;
if(temp == 0)
{
if(j==31)
{
flag[j] = 0;
count ++;
}
if((flag[j+1] == 0)&&(j<31))
{
flag[j] = 0;
count ++;
}
}
n = n/2;
j--;
}
count = 32 - count;
}
return count;
}
};
版本2
class Solution {
public:
int NumberOf1(int n) {
int ans = 0;
while(n != 0){
++ans;
n = n & (n-1);
}
return ans;
}
};