1. 題目描述
輸入一個整數,輸出該數二進制表示中 1 的個數。
2. 解題思路
如果對負數直接右移,會導致最高位一直補1,最終變成0xFFFF死循環。
常規做法:
3. 代碼實現
#include<iostream>
#include<vector>
using namespace std;class Solution {
public:int NumberOf1(int n) {int count = 0;unsigned int flag = 1;while (flag) {if (n & flag) count++;flag = flag << 1;}return count;}
};int main()
{Solution test;int result = test.NumberOf1(10);std::cout << "mian result:" << result << std::endl;return 0;
}