zoukankan      html  css  js  c++  java
  • 剑指Offer 15. 二进制中一的个数

    剑指Offer 15. 二进制中一的个数

    请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。

    示例 1:

    输入:00000000000000000000000000001011
    输出:3
    解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
    

    示例 2:

    输入:00000000000000000000000010000000
    输出:1
    解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
    

    示例 3:

    输入:11111111111111111111111111111101
    输出:31
    解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
    

    方法一

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
     		int cnt = 0;
            while(n != 0){
                //只有最后一位为1 , n&1的值才为1
                cnt += n&1;
                //右移一位
                n >>>1;
            }
            return cnt;
        }
    }
    

    方法二

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
     		int cnt = 0;
            while(n != 0){
                //每次都移除右边第一个1, 例如 1000 & 0111
                n &= (n-1);
                cnt++;
            }
            return cnt;
        }
    }
    
  • 相关阅读:
    预处理器&预处理变量&头文件保护&条件编译
    Xctf攻防世界—crypto—Normal_RSA
    RSA共模攻击
    centos7安装宝塔面板
    cobalt strike出现连接超时情况解决办法
    C语言变量
    Hello World!
    ctfshow—web—web7
    ctfshow—web—web6
    ctfshow—web—web5
  • 原文地址:https://www.cnblogs.com/kikochz/p/13402827.html
Copyright © 2011-2022 走看看