题目描述:
Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
Example
题目思路:
Given x = 123
, return 321
Given x = -123
, return -321
这题需要考虑的corner case我觉得是INT_MIN。这题我先把int分成两部分:sign和正数部分用string来表示。然后用一个long long去算reverse之后的正数部分,再乘以sign。如果overflow就返回0.
Mycode(AC = 44ms):
class Solution {
public:
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
int reverseInteger(int n) {
// Write your code here
// conver the int to sign and string
int sign = n >= 0? 1 : -1;
string strn = to_string(sign * (long long)n);
long long result = 0;
// add to results reversely
for (int i = strn.length() - 1; i >= 0; i--) {
result = result * 10 + int(strn[i]) - int('0');
if (result - 1 >= INT_MAX) {
break;
}
}
result *= sign; // add sign info
if (result >= INT_MAX || result <= INT_MIN) {
return 0;
}
else {
return (int)result;
}
}
};