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.
簡單題,經過上一道噁心的邊界檢測,這道反轉整形數一次AC,只需要考慮邊界溢出,符號亮點。
package leetcode;
public class ReverseInteger {
public static int reverse(int x) {
String s = x+"";
boolean sign = true; //判斷正負
if (s.substring(0, 1).equals("-")){
s = s.substring(1, s.length());
sign = false;
}else if (s.substring(0, 1).equals("+")){
s = s.substring(1, s.length());
sign = true;
}
char[] chars = s.toCharArray();
long ans = 0;
for (int i = chars.length-1; i>=0; i--){
//System.out.println(chars[i] - 48);
//System.out.println(chars[i]);
ans = (long) (ans + Math.pow(10, i) * (chars[i] - 48));
}
if (ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) return 0;
if (!sign) return -(int)ans;
return (int)ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(reverse(-1000000003));
}
}