给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123 输出: 321
示例 2:
输入: -123 输出: -321
示例 3:
输入: 120 输出: 21
解法烂的一批,直接看第二个吧
1 class Solution { 2 public int reverse(int x) { 3 boolean isNeg = false; 4 if(x<0){ 5 x = Math.abs(x); 6 isNeg = true; 7 } 8 String s = String.valueOf(x); 9 Stack<Character> stack= new Stack(); 10 for(int i=0;i<s.length();i++){ 11 stack.push(s.charAt(i)); 12 } 13 s=""; 14 while(!stack.isEmpty()){ 15 s+=stack.pop(); 16 } 17 int res=0; 18 try{ 19 res = Integer.parseInt(s); 20 }catch(Exception e){ 21 System.out.println(0); 22 return 0; 23 } 24 25 if(isNeg){ 26 res = -1 * res; 27 } 28 System.out.println(res); 29 return res; 30 } 31 }
方法2:
int from -2147483648 to 2147483647
为了避免反转越界,指定res为long类型。
1 class Solution { 2 public int reverse(int x) { 3 long res = 0; 4 while(x != 0){ 5 res = res * 10 + x % 10; 6 x = x / 10; 7 if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0; 8 } 9 return (int)res; 10 } 11 }