Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
題目意思:反轉(zhuǎn)一個(gè)int,返回的時(shí)候如果超過32位則返回0
本來(lái)這么簡(jiǎn)單的題目不想寫文章,但是遇到一個(gè)測(cè)試用例莫名其妙的用加負(fù)號(hào)和~a+1的辦法都不能將其變成正數(shù),想了半天原來(lái)是超過int的最大值,將Integer里面的靜態(tài)成員變量輸出一下看到負(fù)數(shù)的值比正數(shù)大一的。只好把int轉(zhuǎn)換成long,再用StringBuilder的字符串反轉(zhuǎn)來(lái)做,也可以用循環(huán)來(lái)做,那樣麻煩一點(diǎn),就是一邊除一邊乘而已。附上我的代碼:
public int reverse(int x) {
StringBuilder a=null;
long temp=x;
if(x>0) {
a =new StringBuilder(""+temp);
}else {
a = new StringBuilder(~temp+1+"");
}
a.reverse();//返回時(shí)判斷是否太大
long b =Long.parseLong(a.toString());
if(b>Integer.MAX_VALUE || b<Integer.MIN_VALUE) {
return 0;
}else if(temp<0) {
return -(int)b;
}else {
return (int)b;
}
}