Sword refers to offer acwing 26 The number of 1 in binary (bit operation)

Topic

Insert picture description here

answer

  1. Conversion of int and unsigned int
int n = -2;
//二进制表示不变,值得含义发生变换,如果是有符号,还表示-2,如果是无符号,表示一个很大的数
unsigned int c = n;   //4294967294
int b = c;   //-2
  1. Binary bit operation
//返回x的最后一位1
int lowbit(int x) {
    
    
    return x & -x;
}

//求n的第k位数字(n是二进制数)
n >> k & 1 ;

Code

class Solution {
    
    
public:

    int lowbit(int x){
    
    
        return x&-x;
    }
    
    int NumberOf1(int _n) {
    
    
        
        unsigned int n=_n;
        
        int res=0;
        while(n) res++,n-=lowbit(n);
        
        return res;
        
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114921114