Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:321

 

Example 2:

Input: -123
Output: -321

 

Example 3:

Input: 120
Output: 21

 

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

32-bit signed integer的补充

  1. 计算机最小的存储单位是“位” 也就是bit或binary digits,用来存放一个二进制数,即 0或1。 8个二进制位为一个字节Byte。 
  2. 对于 16-bit(16位)的计算机,int是以两个字节来储存的,而32-bit的计算机,则是以4个字节,即32个bit来储存的。
  3. 正数用原码存储,负数用补码的形式存储(原码取反加1)
  4. signed的最高位用0,1表示正负,unsigned全部表示数值,以16bit为例,signed的取值范围为(-2^15 to 2^15-1),也就是 -32768 到 +32767的整数,unsigned16位全部用来编码,存储范围便为(0 to 2^16-1),即 0到 65535 的非负整数;
    1. 你可以声明 int a = 1,或者 int a = -1, 但是不可以声明 unsigned a = -1 。但是需要提到的一点是,不管整数的类型是signed 还是 unsigned,都用了16位来存储,也就是说16位全部用来存储数据
    2. signed与unsigned的范围是有交集的,即都包含了0到+32767范围的整数
  5. int占32位的时候,最大可以赋值为:2147483647。也就是0x7fffffff。注意:7的二进制形式最高位为0,如果你对2147483647+1.输出的就是-2147483648。这个数是负数中最大的数,也就是int型可以表示的最小的负数。它的十六进制表示为:0x8fffffff,8的二进制形式最高位是符号位,是1,为负。

代码

import java.util.Arrays;
import java.util.Scanner;

public class ReverInteger {
 public static void main(String[] args) {
  System.out.println("Input:");
  Scanner in=new Scanner(System.in);
  int num=in.nextInt();
  System.out.println("Output:");
  ReverInteger r=new ReverInteger();
  int result=r.reverse(num);
  System.out.println(result); 
 }
 
 public int reverse(int x) {
  int result=0;
  while(x!=0) {
   int tail=x%10;
   int newResult=result*10+tail;
   if((newResult-tail)/10!=result) { //If overflow exists, the new result will not equal previous one.
    return 0;
   }
   result=newResult;
   x=x/10;
  }
  return result;
 }
 
}

 

posted on 2017-12-20 10:14  小兔子的乌龟  阅读(422)  评论(0编辑  收藏  举报