当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Integer 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


相关用法


注:本文由纯净天空筛选整理自ankita_chowrasia大神的英文原创作品 Integer reverse() Method In Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。