Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
Java:
1.http://blog.youkuaiyun.com/linhuanmars/article/details/20024837
public int reverse(int x) {
if(x==Integer.MIN_VALUE) return Integer.MIN_VALUE;
int num=Math.abs(x);
int res=0;
while(num!=0)
{
if(res>(Integer.MAX_VALUE-num%10)/10)
return x>0?Integer.MAX_VALUE:Integer.MIN_VALUE;
res=res*10+num%10;
num/=10;
}
return x>0?res:-res;
}
后面几个解法对越界考虑不全啊 先记大神的吧。
2. http://blog.youkuaiyun.com/myself9711/article/details/11515263
public class Solution {
public int reverse(int x) {
// Start typing your Java solution below
// DO NOT write main() function
int flag = 1;
if(x<0){
flag = -1;
}
int temp = Math.abs(x);
int left = 0;
int result = 0;
while(temp != 0){
left = temp % 10;
result = result*10 + left;
temp = temp/10;
}
if(result > Integer.MAX_VALUE){
return -1;
// only return -1 here, or we can print one message
//or use a static field variable "isValid" for representint states?
}else{
return result*flag;
}
}
}
3. 水印人生:http://gongxuns.blogspot.com/2012/12/leetcode-reverse-integer.html
public class Solution {
public int reverse(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x==0) return x;
boolean neg = x<0;
if(neg) x=-x;
int y=0;
while(x>0){
y=y*10+x%10;
x=x/10;
}
return neg?-y:y;
}
}
4. http://www.cnblogs.com/feiling/p/3371003.html
public int reverse(int x) {
// Note: The Solution object is instantiated only once and is reused by each test case.
boolean positive = (x > 0) ? true : false;
int result = 0;
x = Math.abs(x);
while(x > 0){
result = result * 10 + x % 10;
x = x / 10;
}
if(!positive){
result *= -1;
}
return result;
}