示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
提示:
-231 <= x <= 231 - 1
除10取余,数学推导有点东西
class Solution { public int reverse(int x) { int rev = 0; while(x != 0){ if(rev < Integer.MIN_VALUE / 10 || rev > Integer.MAX_VALUE / 10) //此处为相关数学推导,有点难度 return 0; int digit = x % 10; x /= 10; rev = rev * 10 + digit; } return rev; } }
转载:LeetCode :https://leetcode-cn.com/problems/reverse-integer/solution/