每天一题LeetCode[第六天]
Reverse Integer
Description:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Subscribe to see which companies asked this question.
解题思路:
首先,以为题目很简单,结果把题意理解错了。。。以此为戒,不在犯,在犯就多做一题。。
在真正明白题意已经是看了top solution了,所以,看到他时如何判断是否越界还是佩服,简单 移动,每次数值的变化都是有*10+tail造成的。所以如果会有越界,那也是这里产生的。因此顺势想到,对新的到的值,在逆着运算回去,看看是否等于原来的数就可以判断,是否越界与否。mark,熟悉值的变化,然后可以每做一部,就逆回去看看,是否越界了,其实还有一个更好的方法。就是java对象Integer.MAX_VALUE MIN_VALUE都有具体的值,所以不必做运算,只要做大小判断就可以了!
写了两个版本,区别在于越界判断条件。version1 貌似速度快于version2 。。
Java代码:
public class Solution {
private static final String TAG=Solution.class.getSimpleName();
public int reverse(int x){
// Version 1:
int result=0,tail,newResult;
while (x!=0){
tail=x%10;
x/=10;
newResult=result*10+tail;
//如果-tail在/10后不等于原来的值 则越界
if((newResult-tail)/10!=result){
return 0;
}
result=newResult;
}
return result;
// Version 2:
// long result=0;
// while (x!=0){
// result=result*10+x%10;
// x/=10;
// if(result>Integer.MAX_VALUE || result<Integer.MIN_VALUE){
// return 0;
// }
//
// }
// return (int) result;
}
}
提高代码质量就是,积累精美的思路,优质的细节的过程