LeetCode算法入门- Reverse Integer-day6
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
class Solution {public int reverse(int x) {long result = 0;//取绝对值int temp = Math.abs(x);while(temp > 0){//核心是这里,取反的关键result = result * 10 + temp % 10;temp = temp / 10;}//记得判断是否溢出,这里很关键,这道题的关键if(result > Integer.MAX_VALUE)return 0;if(x >= 0)return (int)result;//这里的符号是另外来进行判断,还有就是强制类型转换,将long强转为intelse return -(int)result;}
}
方法二:将int类型转换为StringBuffer类型,然后调用reverse()方法
class Solution {public int reverse(int x) {int temp = 0;//这里是原因在下面图片if(x == -2147483648)return 0;// temp = -x;elsetemp = Math.abs(x);String str = Integer.toString(temp);//记得要转换为StringBuffer类型才行StringBuffer sb = new StringBuffer(str);String reverseStr = sb.reverse().toString();//将字符串类型转换为长整型(以防它出界)long l = Long.parseLong(reverseStr);if(l > Integer.MAX_VALUE)reverseStr = "0";if(x > 0)return Integer.parseInt(reverseStr);elsereturn -Integer.parseInt(reverseStr);}
}