您的位置:首页 > 其它

[leetcode]_Reverse Integer

2014-05-15 09:27 246 查看
经历了三道树的题后,完全崩溃中,急需一道非树图的题来挽救信心。

题目:反转数字。input : 123 , output : 321.

思路:直接,没什么好说的。

自己代码:很龊,有大量的冗余信息,还申请了一个List,虽然AC了,但有很大改进空间。

public int reverse(int x) {
boolean negative = false;
if(x < 0) {
negative = true;
x = x * (-1);
}
List<Integer> result = new ArrayList<Integer>();
while( x / 10 > 0 ){
result.add(x % 10);
x = x / 10;
}
result.add(x);
int num = 0;
int times = 1;
for(int i = result.size() - 1 ; i >= 0 ; i--){
num += result.get(i) * times;
times *= 10;
}
if(negative) return (-1)*num;
else return num;
}


在网络上看了别人的代码,下面是精简版:(非常清晰,没有什么冗余开销,只用了两个变量)

public int reverse(int x) {
boolean negative = false;
if(x < 0) {
negative = true;
x = x * (-1);
}
int temp = 0 ;
while(x > 0){
temp = temp * 10 + x % 10;
x = x / 10;
}
if(!negative) return temp;
else return (-1)*temp;
}


后面有个知识:负数%正数 等于负数。因此不用对负数单独进行符号判断,可以直接算。

最优版:

public int reverse(int x) {

int temp = 0 ;
while(x != 0){
temp = temp * 10 + x % 10;
x = x / 10;
}
return temp;
}


和第二个版本不同的地方在于while循环的条件由 x > 0 变为了 x != 0,这样负数也能适应该while。只使用了一个变量。五行代码。漂亮。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: