题目:https://leetcode.com/problems/reverse-integer/
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
思路:
这道题不难,关键是要处理溢出问题。代码7、8行,溢出后值会变(这个想法很好)。
https://leetcode.com/discuss/80685/8-ms-simple-c-solution-which-checks-overflow
代码:C++:
class Solution { public: int reverse(int x) { int ans = 0; while (x) { int temp = ans * 10 + x % 10; if (temp / 10 != ans) return 0; ans = temp; x /= 10; } return ans; } };