您的位置:首页 > 其它

7.[LeetCode]Reverse Integer

2016-08-15 23:50 323 查看
我的算法:

public class Solution {
public int reverse(int x) {
boolean isPos = (x >= 0)?true:false;
x = (isPos)?x:(-x);
String num = String.valueOf(x);
StringBuilder numBuilder = new StringBuilder(num);
numBuilder.reverse();
num = numBuilder.toString();
// 处理当 overflow 的情况,返回0
try{
x = Integer.valueOf(num);
} catch(NumberFormatException e){
return 0;
}

if(!isPos){
x = -x;
}
return x;
}
}


大神算法:

public class Solution {
public int reverse(int x) {
boolean isPos = x>0;
if(!isPos)
x = x* -1;
int ans = 0, tmp = 0;
while(x>0){
if( (ans) > (Integer.MAX_VALUE/10)) return 0;// overflows
ans = ans* 10 + x % 10;
x /=10;
}
return isPos? ans: -1*ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode