Reverse Integer
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
public class Solution {
public int reverse(int x) {
String a = String.valueOf(x);
long re = 0;
long danwei = 1;
if (a.charAt(0)-'-'==0) {
int n=a.length();
int i = 1;
while (i<n) {
re += (a.charAt(i)-'0')*danwei;
i++;
danwei = danwei*10;
}
re = -re;
}
else {
int n=a.length();
int i = 0;
while (i<n) {
re += (a.charAt(i)-'0')*danwei;
i++;
danwei = danwei*10;
}
}
if(re>Integer.MAX_VALUE){
return 0;
}
if(re<Integer.MIN_VALUE) {
return 0;
}
return (int)re;
}
}
本文介绍了一种用于反转整数的算法实现,通过字符串操作来处理正负号,并使用长整型变量防止反转过程中可能出现的溢出问题。文章还讨论了特殊输入情况如以0结尾的整数处理方式。
1499

被折叠的 条评论
为什么被折叠?



