Reverse Integer (Easy)

Description

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Analysis

翻转数字。问题在于翻转之后的数字可能越界。如果越界则返回0.
我的方法比较笨= =。翻转两次判断答案和原来的x是否相等。特判10的倍数。

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//C++
class Solution {
public:
int reverse(int x) {
int flag = 1,y = 0 ,z = 0,tx,ty;
if(x<0){
flag = -1;
x = -x;
}
tx = x;
while(x){
y = y*10+x%10;
x/=10;
}
ty = y;
while(y){
z = z*10+y%10;
y/=10;
}
if(z==tx||tx%10==0)
return flag*ty;
else
return 0;
}
};