Reverse digits of an integer.
Example1: x = 123, return 321
开始的时候我写的while(temp),报错了,不能这么用么...
Example1: x = 123, return 321
Example2: x = -123, return -321
这个开始的时候就想要用一个flag,判断下正负,应该就OK 了
public class Solution {
public int reverse(int x) {
int temp;
int flag = x > 0 ? 1 : -1;
int result = 0;
temp = Math.abs(x);
while(temp != 0) {
result = result * 10 + temp % 10;
temp /= 10;
}
result *= flag;
return result;
}
}
开始的时候我写的while(temp),报错了,不能这么用么...
查阅资料发现,其实不用检查符号,直接搞就可以了!
public class Solution {
public int reverse(int x) {
int result = 0;
//while(x)
while(x != 0) {
result = result * 10 + x % 10;
x /= 10;
}
return result;
}
}