英文:
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;
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论