目录

题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
解决方案
1 2 3 4 5 6 7 8 9 10 11
| public class Solution { public int reverse(int x) { String s = String.valueOf(x); if(x < 0) s = s.substring(1, s.length()); StringBuilder builder = new StringBuilder(); for(int i = s.length() - 1; i>=0; i--) builder.append(s.charAt(i)); if((x > 0 && builder.length() == 10 && builder.toString().compareTo("2147483647") > 0) || (x < 0 && builder.length() == 10 && builder.toString().compareTo("2147483648") > 0)) return 0; int res = Integer.valueOf(builder.toString()); return x > 0 ? res : 0 - res; } }
|
注意事项
- 转换为字符串考虑,注意正负情况和边界溢出情况。