[LintCode] Reverse Integer 翻转整数

时间:2024-01-17 21:39:14

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 = ;
while (n != ) {
res = * res + n % ;
n /= ;
}
return (res < INT_MIN || res > INT_MAX) ? : res;
}
};

解法二:

class Solution {
public:
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
int reverseInteger(int n) {
int res = ;
while (n != ) {
int t = res * + n % ;
if (t / != res) return ;
res = t;
n /= ;
}
return res;
}
};