Leetcode【191】Number of 1 Bits

这道题的输入是一个无符号的整数

有两种办法

解法一、暴力解

把整数变成字符串,遍历字符串查找1的个数,注意,这里不能用String.valueOf

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        String str = Integer.toBinaryString(n);
        int count = 0;
        for(int i = 0; i < str.length();i++){
            char a = str.charAt(i);
            if(a == '1')
                count++;
        }
        return count;
    }
}

解法二、位运算

用31个0和1个1和每一位做与操作,如果该位是1则结果为1,否则为0

与操作的规则是两个都是1则为1,否则为0

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        int mask = 1;
        for(int i = 0; i < 32; i++){
            if ((n & mask) != 0) {
                res++;
            }
            mask<<=1;
        }
        return res;
    }
发布了214 篇原创文章 · 获赞 72 · 访问量 152万+

猜你喜欢

转载自blog.csdn.net/ssjdoudou/article/details/103946956