Posted onEdited onInLeetCodeDisqus: Symbols count in article: 781Reading time ≈1 mins.
O(n) time O(1) space
1 2 3 4 5 6 7 8 9 10
classSolution: defreverse(self, x: int) -> int: res, MAX = 0, (1 << 31) - 1 sign = -1if x < 0else1 x = abs(x) while x > 0: res = res * 10 + x % 10 x //= 10 if res > MAX: return0 return res * sign
这道题不需要保存负号,直接转即可
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: intreverse(int x){ long res = 0; while (x) { res = res * 10 + x % 10; x /= 10; if (res < INT_MIN || res > INT_MAX) return0; // 只要invalid就返回 } return res; } };
O(n) time O(n) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intreverse(int x){ if (x == INT_MIN || x == 0) return0; int sign = x < 0 ? -1 : 1; x = abs(x); string s = to_string(x); while (!s.empty() && s.back() == '0') s.pop_back(); long res = 0; for (auto rit = s.rbegin(); rit != s.rend(); ++rit) { res = res * 10 + *rit - '0'; if (res > INT_MAX) return0; } return sign * res; } };