Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
first iteration:
class Solution {
public:
int reverse(int x) {
bool neg = (x < 0);
if (neg) {
x = abs(x);
}
int ret = 0;
while(x>0) {
// overflow check
if (ret > std::numeric_limits<int>::max()/10) {
return 0;
}
<pre name="code" class="cpp" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 30px;"> // assume ret is partial result achieved already, multiply it by 10 and then add residual (below)
ret *= 10;
// overflow check
if (ret > std::numeric_limits<int>::max()-x%10) { return 0; } ret += x%10; x /= 10; } return neg ? -ret : ret; }};
2nd iteration:
class Solution {
public:
int reverse(int x) {
bool isNeg = (x < 0);
if (isNeg) {
x = abs(x);
}
int ret = 0, lastDigit = 0;
while(x>0) {
lastDigit = x%10;
ret = 10*ret + lastDigit;
x /= 10;
}
// overflow check, positive number ==> negative
if (ret < 0) {
return 0;
}
return isNeg ? -ret : ret;
}
};