标签:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Solution1:
这道题做的太麻烦了,corner case很多,碰到负数不知道怎么给reverse。强行转成string用long来处理overflow,暴力又麻烦!!
public class Solution { public int reverse(int x) { String check=String.valueOf(x); String res; if(check.charAt(0)==‘-‘) { res="-"; res+=transfer(check.substring(1)); long m=Long.parseLong(res); if(m<=Integer.MIN_VALUE) { return 0; } else { return Integer.parseInt(res); } } else { res=transfer(check); long m=Long.parseLong(res); if(m>=Integer.MAX_VALUE) { return 0; } } return Integer.parseInt(res); } public String transfer(String s1) { StringBuilder sb=new StringBuilder(); Character prev=‘0‘; for(int i=s1.length()-1;i>=0;i--) { sb.append(s1.charAt(i)); } if(sb.length()!=1) { while(sb.charAt(0)==‘0‘) { sb.deleteCharAt(0); } } return sb.toString(); } }
parseInt用法:https://www.dotnetperls.com/parseint-java
Solution 2:
用int sign判断会快很多。不明白为什么while(x!=0)就报错,诡异。。。。
public class Solution { public int reverse(int x) { int sign=(x>=0)?1:-1; x=Math.abs(x); int res=0; while(x>0) { if(res>Integer.MAX_VALUE/10) { return 0; } res=res*10+x%10; x/=10; } return res*sign; } }
标签:
原文地址:http://www.cnblogs.com/Machelsky/p/5860894.html