数字中的位反转

20
例如,我有二进制数1011,它等于十进制数11。我想要反转位的位置,使其变成1101,即十进制数13。以下是代码:

例如,我有二进制数1011,它等于十进制数11。我想要反转位的位置,使其变成1101,即十进制数13。以下是代码:

import java.util.*;
public class bits {
    public static void main(String[] args) {
        Scanner scnr=new Scanner(System.in);
        System.out.println("enter x:");
        int x=scnr.nextInt();
        int b=0;
        while (x!=0){
            b|=( x &1);
            x>>=1;
            b<<=1;
        }
        System.out.println(b);
    }
}

但是当我输入 x 11 时,它打印出来的是 26。错在哪里了?


3
一个完整的整数可以使用 Integer.reverse(int i) 进行反转 - 但是看起来你想要反转比特数更少的整数,我将其留作注释。 - Andreas Dolk
1
看起来解决方案已经在这里了: https://dev59.com/vnRB5IYBdhLWcg3wAjXR 你忽略了最后需要进行额外的移位。 - AndrewB
13个回答

0
//    i/p=3 
//    o/p=3221225472
// Clearly observe the 1L while doing the left shift, if ignored it will fail to return the expected output dur to mismatch in bit size.

    public static long reverse(long n) {
        long rev = 0;
        for(int i = 31; i >=0; i--){
            if((n & 1<<i) != 0){
                rev = rev | 1L<<(31-i);
            }
        }
        return rev;
    }

0

在 while 循环中使用无符号右移运算符(>>>)是安全的,可以避免负数进入无限循环的危险。

while (x!=0){
  b<<=1;
  b|=( x &1);
  x>>>=1;
}

0

结果是预期的两倍,因此最后一次左移操作(一个左移操作将值加倍)太多了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接