他们怎么会不一样呢?

问题描述 投票:0回答:1
public class Solution {
    public static int countSetBits(int n) {
        // Write your code here.
        int count = 0;
        while(n>0) {
            int bits = n&1;
            if(bits == 1)
            
            count++;
            n=n>>1;
            

        }
        return count;
    }
}
public class Solution {
    public static int countSetBits(int n) {
        // Write your code here.
        int count = 0;
        while(n>0) {
            int bits = n&1;
            if(bits == 1)
            {
            count++;
            n=n>>1;
            }

        }
        return count;
    }
}

我试过两个代码 在第一个代码中,输出一直显示到值超过 7 时才显示任何内容 但是第二个工作得很好

java loops bit
1个回答
0
投票

在第一个中,

if
条件仅适用于
count++
。在第二个中,大括号表示
if
条件适用于以下两个语句。这使得代码产生不同的结果。

© www.soinside.com 2019 - 2024. All rights reserved.