📜  Java中的整数reverse()方法

📅  最后修改于: 2022-05-13 01:54:40.725000             🧑  作者: Mango

Java中的整数reverse()方法

Java.lang.Integer.reverse() 是Java中的一个内置方法,用于返回指定int 值的二进制补码二进制表示中位的倒序。

句法:

public static int reverse(int a)

参数:参数a是一个整数值,其位将被反转。

返回值:该方法返回将指定int值中位的顺序颠倒得到的值。

例子:

Input: 86
Output: 1778384896
Explanation:
Consider an integer a = 86
Binary Representation = 1010110
The number of one bit = 4 
After reversing it is = 1778384896

Input: 168
Output: 352321536

下面的程序说明了Java.lang.Integer.reverse() 方法:
程序 1:对于正数。

// Java program to illustrate the
// Java.lang.Integer.reverse() method
import java.lang.*;
  
public class geeks {
  
    public static void main(String[] args)
    {
  
        int a = 168;
        System.out.println("Number = " + a);
  
        // It returns the value obtained by reversing order of the bits
        System.out.println("By reversing we get = " + Integer.reverse(a));
    }
}
输出:
Number = 168
By reversing we get = 352321536

程序 2:对于负数。

// Java program to illustrate the
// Java.lang.Integer.reverse() method
import java.lang.*;
  
public class geeks {
  
    public static void main(String[] args)
    {
  
        int a = -72;
        System.out.println("Number = " + a);
  
        // It returns the value obtained by reversing order of the bits
        System.out.println("By reversing we get = " + Integer.reverse(a));
    }
}
输出:
Number = -72
By reversing we get = 503316479

程序 3:对于十进制值和字符串。
注意:当十进制值或字符串作为参数传递时,它会引发错误消息。

// Java program to illustrate the
// Java.lang.Integer.reverse() method
import java.lang.*;
  
public class geeks {
  
    public static void main(String[] args)
    {
  
        int a = 37.9;
        System.out.println("Number = " + a);
  
        // It returns the value obtained by reversing order of the bits in
        // the specified int value
        System.out.println("By reversing we get = " + Integer.reverse(a));
        a = "21";
        System.out.println("Number = " + a);
  
        // It returns the value obtained by reversing order of the bits in
        // the specified int value
        System.out.println("By reversing we get = " + Integer.reverse(a));
    }
}
输出:
prog.java:9: error: incompatible types: possible lossy conversion from double to int
    int a = 37.9;
            ^
prog.java:17: error: incompatible types: String cannot be converted to int
     a = "21";
         ^
2 errors