Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Example2: x = -123, return -321
Analysis:
Simple question. Just be careful with the last digit and positive/negative.Also be careful with the corner cases.
Idea is to keep x/10 for the original int and *10 for the result int + x%10.
Note that in Python, when compute -1/10 the result is -1 not the expected 0.
This is because the "floor" function for the int division.
E.g., math.floor(0.89) = 0
math.floor(-0.89) = -1
So I check the positive and negative sign in the python code.
The number 214748364 in python code is the maxint/10 = 2147483647/10.
Code(C++):
class Solution {
public:
int reverse(int x) {
int res = 0;
while (x!=0){
if (res > INT_MAX/10 || res < INT_MIN/10){
return 0;
}
res = res*10+ x%10;
x= x/10;
}
return res;
}
};
Code (Python):
class Solution:
# @return an integer
def reverse(self, x):
res = 0
if x>=0:
pos = True
else:
pos = False
x = -x
while not x == 0:
if res > 214748364:
return 0
else:
res = res*10 + x%10
x = x/10
if pos:
return res
else:
return -res
What about the overflow cases?
ReplyDeleteSorry, I don't really get what you mean by overflow cases, could you give an example?
DeleteAssuming an integer is 32-bits, if x = 2147483643, the reversed integer would be 3463847712, which certainly overflows. I think you need to handle this in your code, cause otherwise the problem is just too trivial and meaningless. Also, it is not necessary to check whether x is positive or not, just replace the termination condition of while loop with x!=0 and your code will handle all positive and negative cases correctly.
Deletejust take a bigger type for res such as long , and put an extra condition saying if res > INT_MAX return 0
Deletecan anyone explain why this weird test case:
DeleteInput: 1534236469
Output: 1056389759
Expected: 0
@Yu Zhu are you sure your either of above solution got accepted at leetcode ?
Deletebecause I got WA :
Input: 1534236469
Output: 1056389759
Expected: 0
you didn't take care of overflow cases. Did you?
Thanks for your reply, I think it might because this post was written long time ago and leetcode oj has changed some of the test cases. Now I have changed the code and tested on OJ.
DeleteThanks.
Thanks great help ..!!!!!!!!!!!!!
ReplyDelete