Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
反转数字的整数。
示例1:x = 123,返回321
示例2:x = -123,返回-321
注意:
假定输入为32位有符号整数。 当反转的整数溢出时,你的函数应该返回0。
做LeetCode我个人最大的缺点就是上来就干,因为英语毕竟没有中文看着方便,导致好多提示根本没有注意。如本题溢出时返回0。
1 class Solution { 2 public int reverse(int x) { 3 boolean isAbove=true; 4 StringBuffer sBuffer=new StringBuffer(); 5 int newX=x; 6 if (x < 0) { 7 isAbove = false; 8 x = Math.abs(x); 9 } 10 while (x > 0) { 11 sBuffer.append(x % 10); 12 x = x / 10; 13 } 14 if (newX!=0) { 15 try { 16 if (isAbove) 17 return Integer.parseInt(sBuffer.toString()); 18 else 19 return -Integer.parseInt(sBuffer.toString()); 20 } catch (Exception e) { 21 return 0; 22 } 23 24 } 25 else 26 return 0; 27 } 28 }
顺道来复习下JAVA基本数据类型的数值范围:
byte的取值范围为-128~127,占用1个字节(-2的7次方到2的7次方-1)
short的取值范围为-32768~32767,占用2个字节(-2的15次方到2的15次方-1)
int的取值范围为(-2147483648~2147483647),占用4个字节(-2的31次方到2的31次方-1)
long的取值范围为(-9223372036854774808~9223372036854774807),占用8个字节(-2的63次方到2的63次方-1)