Problem : Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
1.C++版
class Solution {
public:
int reverse(int x) {
if(0 == x){
return 0;
}
int sign = x > 0 ? 1 : -1;
int result = 0;
x = abs(x);
while(0 != x){
result = result * 10 + x % 10;
x = x / 10;
}
return result * sign;
}
};
2.Java版
public class Solution {
public int reverse(int x) {
if(0 == x){
return 0;
}
int sign = x > 0 ? 1 : -1;
int result = 0;
x=Math.abs(x);
while(0 != x){
result = result * 10 + x % 10;
x = x /10;
}
return result*sign;
}
}
3.Python版