Leetcode题解之其他(1)位1的个数

题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/26/others/64/

题目描述:

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

示例 :

输入: 11
输出: 3
解释: 整数 11 的二进制表示为 00000000000000000000000000001011

示例 2:

输入: 128
输出: 1
解释: 整数 128 的二进制表示为 00000000000000000000000010000000

思路:用for 循环 每次将最高位右移动到最低位,再与 1(00000000000000000000000000000001) 进行 与 运算。

代码:

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count=0;
        for(int i = 31;i >= 0; i--){
            if((n >>> i & 1)==1)
                count++;
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34433210/article/details/84583443
今日推荐