2016. 3. 19
inverse integer:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Example2: x = -123, return -321
consideration:
思路比较简单直接,但是博主考虑到restore x 的问题, 然而网上大家都没有考虑相应问题, 题目也没有要求restore 故此处不管。 具体面试的时候可以问考官。
***** 但是要考虑overflow 问题。
The input can be in int range but the output might overflow , for example, if you input (INT_MAX-1), the output will be out of range.
Till now, two solutions for it.
1. Change return answer to long type
2. set upper bound and lower bound to detect
talk is cheap, show the code :
public class Solution {
public int reverse(int x) {
int res = 0;
while(x != 0){
int lastD = x % 10 ;
int upBound = (Integer.MAX_VALUE - lastD) / 10 ;
int loBound = (Integer.MIN_VALUE - lastD) / 10 ;
if (x>0 && res > upBound) return 0;
if (x<0 && res < loBound) return 0;
x = x / 10 ;
res = res * 10 + lastD ;
}
return res;
}
}
btw 这题也可以用recursion 做 就不写了这次。 因为overflow问题 耽误时间较长希望下次改进。
No comments:
Post a Comment