Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
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; } };
本文转自博客园Grandyang的博客,原文链接:翻转整数[LintCode] Reverse Integer ,如需转载请自行联系原博主。