LintCode 二级制中有多少个1

public class Solution {
    /**
     * @param num: an integer
     * @return: an integer, the number of ones in num
     */
     
     /*
        负数的二进制是其绝对值的补码(反码+1)
        1 源码:  0001
        1 反码:  1110
        1 补码:  1111
         -1     :   1111
     */
    public int countOnes(int num) {
        // write your code here
         int countZero=0,countOne=0;
         int abs=num;
         boolean isPlus=true;  //正数
         if(num<0)
         {
            abs=Math.abs(num+1);
            isPlus=false;
             
         }
         int index=32;
         while(abs!=0)
         {
           
             if((abs%2==1 && isPlus )|| (!isPlus && abs%2==0))
             {
                 countOne++;
             }
             abs>>=1; //右移1 相当于除2
             index--;
         }
         if(num<0)
            countOne+=index;  //负数要往前面补一
        return countOne;
    }

};

posted @ 2017-09-08 09:43  temporary  阅读(139)  评论(0编辑  收藏  举报