剑指offer 15:二进制中1的个数

题目描述

输入一个整数,输出该数32位二进制表示中1的个数。其中负数用补码表示。
 
复杂解法:手动计算二进制,然后计算1的个数,这里要注意负数的计算,
class Solution {
public:
     int  NumberOf1(int n) {
         if(n==0) return 0;
         if(n == INT_MIN ) return 1;
         int zn = abs(n);
         string str = toBinary(zn);
         int count = 0;
         int i=str.length()-1;
         if(n<0){
             while(str[i]=='0')
                 i--;
         }
         for(;i>=0;i--){
             if(str[i]=='1')
                count++;
         }
         if(n>0)
             return count;
         else{
             return 32-str.length()+count;
         }
     }
     string toBinary(int n){
         string str = "";
         while(n>0){
             str += to_string(n % 2);
             n /= 2;
         }
         str.reserve();
         return str;
     }
    
};

 上述解法太过繁琐,应利用二进制的一些特性来进行计算。

超级简单容易理解 &(与)

把这个数逐次 右移 然后和1 与,

就得到最低位的情况,其他位都为0,

如果最低位是0和1与 之后依旧 是0,如果是1,与之后还是1。

对于32位的整数 这样移动32次 就记录了这个数二进制中1的个数了

class Solution {
public:
     int  NumberOf1(int n) {
         int count = 0;
         while(n!=0){
             count += n & 1;
             n = ((unsigned int)n)>>1;//转化为无符号数然后右移
         }
         return count;
     }
};

  

public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        while(n!= 0){
            count += n & 1;
            n = n>>>1;//无符号右移
        }
        return count;
    }
}
原文地址:https://www.cnblogs.com/ttzz/p/13837115.html