Reverse digits of an integer.Example1: x = 123, return 321
Example2: x = -123, return -321java
时间 O(n) 空间 O(n)git
先将数字转化为字符串,而后将字符串倒序输出,并转回数字。记得须要去除首部多余的0。优化
时间 O(n) 空间 O(1)code
经过对数字模十取余获得它的最低位。其实本题考查的是整数相加的溢出处理,检查溢出有这么几种办法:rem
public class Solution { public int reverse(int x) { long result = 0; int tmp = Math.abs(x); while(tmp>0){ result *= 10; result += tmp % 10; if(result > Integer.MAX_VALUE){ return 0; } tmp /= 10; } return (int)(x>=0?result:-result); } }
2018/10字符串
func reverse(x int) int { // The reserse of MinInt32 will overflow if x == math.MinInt32 { return 0 } sign := 1 // Handle negative numbers if x < 0 { x = -x sign = -1 } result := 0 for x > 0 { rem := x % 10 // When the result == MaxInt32/10, the reminder has to be smaller than 7 // so that result*10 + rem won't overflow (MaxInt32 is 2147483647) if math.MaxInt32/10 < result || (math.MaxInt32/10 == result && rem > 7) { return 0 } result = result*10 + rem x = x / 10 } return result * sign }
Q:拿到反转整数题目后第一步是什么?
A:先问出题者尾部有0的数字反转后应该是什么形式,其次问清楚溢出时应该返回什么。编译器
Q:除了检查溢出返回特定值之外,有没有别的方法处理溢出?
A:能够使用try-catch代码块排除异常。it