zoukankan      html  css  js  c++  java
  • 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;
        }

    };

  • 相关阅读:
    路由懒加载的实现
    vue中的tab栏切换内容变换
    H5页面的高度宽度100%
    vue中的路由的跳转的参数
    xxxx-xx-xx的时间的加减
    sql server 2008 R2 备份还原到sql 2012
    eval方法将字符串转换成json对象
    CSS3 圆角(border-radius)
    [Easyui
    JavaScript slice() 方法
  • 原文地址:https://www.cnblogs.com/temporary/p/7493049.html
Copyright © 2011-2022 走看看