題目描述:
輸入一個整數,輸出該數二進制表示中1的個數。其中負數用補碼錶示。
可能首先會想到,每次把這個數進行除以2,或者進行右移操作,但是考慮到負數的情況,並不適用
可以藉助一個flag, 保持n不動,而每次左移flag(這個flag是unsigned類型)
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include<cmath>
#include<algorithm>
using namespace std;
class Solution {
public:
int NumberOf1(int n) {
int count=0;
unsigned int flag=1;
while(flag!=0) {
if((n&flag)!=0) {
count++;
}
flag=flag<<1;
}
return count;
}
};
另有一種更簡潔,更快速的辦法,n&(n-1)每次將n最右邊的1變爲0,複雜度與n中1的個數有關:
class Solution {
public:
int NumberOf1(int n) {
int count=0;
while(n) {
n=n&(n-1);
count++;
}
return count;
}
};