Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
Have you met this question in a real interview?
Example
Given x = 123
, return 321
Given x = -123
, return -321
LeetCode上的原题,请参见我之前的博客Reverse Integer。
解法一:
class Solution { public: /** * @param n the integer to be reversed * @return the reversed integer */ int reverseInteger(int n) { long long res = 0; while (n != 0) { res = 10 * res + n % 10; n /= 10; } return (res < INT_MIN || res > INT_MAX) ? 0 : res; } };
解法二:
class Solution { public: /** * @param n the integer to be reversed * @return the reversed integer */ int reverseInteger(int n) { int res = 0; while (n != 0) { int t = res * 10 + n % 10; if (t / 10 != res) return 0; res = t; n /= 10; } return res; } };
时间: 2024-10-26 18:54:44