LeetCode:计算1的位数

huangapple go评论74阅读模式
英文:

LeetCode: count number of 1 bits

问题

我正在尝试理解为什么下面的代码在这个问题中不起作用

我们将位0和1作为参数传递如果我不使用位运算而是首先将整数转换为charArray然后迭代它以计算'1'的数量最后返回它为什么它不起作用

public class Solution {
    // 你需要将n视为无符号值
    public int hammingWeight(int n) {
         int count=0;
        for(char c:String.valueOf(n).toCharArray())
        {
            if('1'==c)
                ++count;
        }
        
        return count;
        
    }
}
英文:

I am trying to understand why below code won't work for this problem.

We are passing bits (0's & 1's) as an argument. If I do not use Bit operations and rather I first convert the integer to charArray and iterate over it to count the no of '1' and then return it, why it does not work?

 public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
             int count=0;
            for(char c:String.valueOf(n).toCharArray())
            {
                if('1'==c)
                    ++count;
            }
            
            return count;
            
        }
    }

答案1

得分: 1

你正在一个十进制字符串中计数1,你可以通过Integer.toBinaryString()轻松将其转换为二进制字符串。

public int hammingWeight(int n) {
    int count = 0;
    for (char c : Integer.toBinaryString(n).toCharArray()) {
        if ('1' == c)
            ++count;
    }

    return count;
}
英文:

You are counting 1 in a decimal string, you can eaily convert it to a binary string by Integer.toBinaryString()

public int hammingWeight(int n) {
    int count=0;
    for(char c:Integer.toBinaryString(n).toCharArray())
    {
        if('1'==c)
            ++count;
    }

    return count;

}

答案2

得分: 0

鉴于这是Java,我很惊讶没有人提到过java.lang.Integer的JDK方法Integer.bitCount(i)

英文:

Given this is Java, I am surprised nobody mentioned the JDK method Integer.bitCount(i) of java.lang.Integer.

答案3

得分: -1

我们不需要将n转换为字符串,这将通过得很好:

class Solution {
    public static int hammingWeight(int n) {
        int ones = 0;
        while (n != 0) {
            ones = ones + (n & 1);
            n = n >>> 1;
        }
        return ones;
    }
}
英文:

We don't have to convert the n to string, this would pass just fine:

class Solution {
    public static int hammingWeight(int n) {
        int ones = 0;
        while (n != 0) {
            ones = ones + (n & 1);
            n = n>>>1;
        }
        return ones;
    }
}

huangapple
  • 本文由 发表于 2020年9月5日 11:50:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63750276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定