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;
        }

    };

  • 相关阅读:
    剑指 Offer II 005. 单词长度的最大乘积
    中文编程的瓶颈
    Unity TextMeshPro 富文本格式介绍
    centos使用httpd搭建文件下载服务器教程
    开博第一天
    macOS安装brew(Homebrew国内源)
    git命令将代码导出为单个文件
    CPU虚拟化
    指令
    华为公有云服务的主要服务产品
  • 原文地址:https://www.cnblogs.com/temporary/p/7493049.html
Copyright © 2011-2022 走看看