有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

位操作有人知道为什么我的java代码使用n=n/2不能正常工作,而n>>1能正常工作吗?

这是leetcode(https://leetcode.com/problems/number-of-1-bits/)的一个问题。 这个方法是用来计算这个数字在二进制中的1。 我尝试使用n=n/2,当n=n>>;我知道。有人知道为什么吗

public class Numberof1Bits {

public static void main(String[] args) {
    System.out.println(new Numberof1Bits()
            .hammingWeight(0b11111111111111111111111111111111));
}

public int hammingWeight(int n) {
    int count = 0;
    if (n < 0)
        count++;
    for (int i = 0; i < 31; i++) {
        if ((n & 1) == 1)
            count++;
        n = n >> 1;// while this doesn't work when n=n/2;
    }
    return count;
}
}

共 (1) 个答案

  1. # 1 楼答案

    你使用的是无符号整数。0xFFFFFF=-1-1>>;1 = -1. -1/2 = 0. 对于设置了最高有效位的任何数字,它都将失败

    如果是Java,>>运算符执行符号扩展的按位右移。例如(为了清晰起见,我使用8位数字):

    0b10111111 >> 1 => 0b11011111
    

    十进制数相同:

    -65 >> 1 => -33
    

    位右移一个位置,最高有效位保持原样。我的示例数字(0B1011111)是十进制的-65。如果你把它除以二,得到-32。是的,我们在翻译中损失了一点/2执行算术除法,这相当于>> 1用于正数

    在支持无符号整数和无符号右移的语言中,n/2应该按预期工作

    在java中,由于>>是有符号的,因此可以使用>>>进行右移,而不使用符号扩展,以及可能更快的循环:

    public int hammingWeight(int n) {
        int count = 0;
        while(n != 0) {
            if ((n & 1) != 0) {
                count++;
            }
            n = n >>> 1;
        }
        return count;
    }