techiall / Blog

🍋 [My Blog] See discussions
https://github.com/techiall/Blog/discussions
MIT License
8 stars 1 forks source link

Leetcode | 位1的个数 #47

Open techiall opened 5 years ago

techiall commented 5 years ago

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

示例 1:

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

示例 2:

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

示例 3:

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

提示:

进阶: 如果多次调用这个函数,你将如何优化你的算法?

java

二进制中 1 的个数,首先会联想到 位运算。

这道题目我们可以用 与运算 &,和这个数的每一位作比较,有 1 的位累加起来即可。

Java 要看作无符号,所以在进行位运算的时候,要使用无符号的左移(<<<)或者右移(>>>)。

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