標籤:
題目描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
解題思路:
這道題比較簡單,只要注意兩個問題:1,輸入可能有123,-123兩種情況。2,可能會出現值溢出的情況,所以先用long類型處理,決定沒有溢出後再轉換為int
具體代碼:
1 public static int reverse(int x) { 2 String s =""+x; 3 char[] array=s.toCharArray(); 4 if(array[0]==‘-‘){ 5 reverse(array,1); 6 Long num=Long.valueOf(new String(array)); 7 if(num<Integer.MIN_VALUE){ 8 return 0; 9 }10 return Integer.valueOf(new String(array));11 12 }13 else{14 reverse(array,0);15 Long num=Long.valueOf(new String(array));16 if(num>Integer.MAX_VALUE){17 return 0;18 }19 return Integer.valueOf(new String(array));20 }21 22 }23 public static void reverse(char[] array,int from){24 int to = array.length-1;25 while(from<to){26 char ch=array[from];27 array[from]=array[to];28 array[to]=ch;29 from++;30 to--;31 }32 }
【leetcode】7. Reverse Integer