題目
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
思路
每次左移一位,進行&運算。
代碼
/*------------------------------------------------------
* 日期:2014-04-12
* 作者:SJF0115
* 題目: 191.Number of 1 Bits
* 網址:https://leetcode.com/problems/number-of-1-bits/
* 結果:AC
* 來源:LeetCode
* 博客:
--------------------------------------------------------*/
#include
#include
using namespace std;
class Solution {
public:
int hammingWeight(uint32_t n) {
if(n == 0){
return 0;
}//if
if(n == 1){
return 1;
}//if
int count = 0;
for(int i = 0;i < 32;++i){
if((n&(1< 0){
++count;
}//if
}//for
return count;
}
};
int main(){
Solution solution;
uint32_t num = 1;
cout<<""<
思路二
每執行一次x = x&(x-1),會將x用二進制表示時最右邊的一個1變為0,因為x-1將會將該位(x用二進制表示時最右邊的一個1)變為0。
代碼二
/*------------------------------------------------------
* 日期:2014-04-12
* 作者:SJF0115
* 題目: 191.Number of 1 Bits
* 網址:https://leetcode.com/problems/number-of-1-bits/
* 結果:AC
* 來源:LeetCode
* 博客:
--------------------------------------------------------*/
#include
#include
using namespace std;
class Solution {
public:
int hammingWeight(int n) {
int count = 0;
while(n != 0){
n = n & (n-1);
count++;
}//while
return count;
}
};
int main(){
Solution solution;
uint32_t num = 11;
cout<<""<