Example1: x = 123, return 321 Example2: x = -123, return -321
分析
把一个数字倒过来,题目不难,需要考虑的是边界情况,如果越界,返回0
解决方案1(python)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Solution: def reverse(self, x: int) -> int: INT_MIN, INT_MAX = -2**31, 2**31-1 result = 0 while x != 0: if result < INT_MIN // 10 + 1 or result > INT_MAX // 10: return 0 nowDigit = x % 10 if x < 0 and nowDigit < 10: nowDigit -= 10 x = (x - nowDigit) // 10 result = result * 10 + nowDigit return result
解决方案2(C++)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intreverse(int x){ longlong result = 0; while(x != 0) { int now = x % 10; result = result * 10 + now; if(result > INT_MAX || result < INT_MIN) { return0; } x = x / 10; } return result; } };
func reverse(x int) int { result := 0 for x != 0 { if result < math.MinInt32 / 10 || result > math.MaxInt32 / 10 { return 0 } nowDigit := x % 10 x /= 10 result = result * 10 + nowDigit } return result }