標籤:
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; }}
7. Reverse Integer