2019-06-03剑指统计二进制中的1

class Solution {
public:
     int  NumberOf1(int n) {
         int cnt=0;
         while(n){
             cnt++;
             n=n&(n-1);
         }
         return cnt; 
     }
};

python跳不出循环。是因为python没有对负数限定位。它的符号位可以无限制增长。

class Solution {
public:
    int hammingWeight(uint32_t n) {
         int cnt=0;
         int t=1;
         int i=0;
         for(int i=0;i<31;i++){
             if (n&t){
                 cnt++;
                 //cout<

边界条件错了。最后循环没有找到32位的数

class Solution {
public:
    int hammingWeight(uint32_t n) {
         int cnt=0;
         unsigned int t=1; #关键,不然移动31位报错为负
         while(t){
             if (n&t){
                 cnt++;
                 //cout<

用usigned int 才能移动到负位

你可能感兴趣的:(2019-06-03剑指统计二进制中的1)