-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Integer
75 lines (56 loc) · 1.49 KB
/
Reverse Integer
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Description:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Seen this question in a real interview before? YesNo
class Solution {
public:
int reverse(int x) {
char *values=new char[33];
string temp;
temp=to_string(x);
const char *k;
k=temp.c_str();
int a=temp.size();
for(int i=a;i>=1;i--){
values[a-i]=k[i-1];
}
int result;
result=atoi(values); ///use array is Complicated and cumbersome,and sometimes it could be quite error
if(x>=0){
result=result;
}else{
result=-result;
}
return result;
}
};
This solution is not good and it can't pass.but use clion it can success,I think it's complicated.actually; in fact; it is so easy
int reverse(int x){
long long r=0;
long long t=x;
t=t>0?t:-t;
for(;t;t/=10)
r=r*10+t%10;
bool sign=x>0?false:true;
if(r>2147483647||(sign&&r>2147483648){
return 0;
}else{
if(sign){
return -r;
}else{
return r;
}
}
}
};
Through this procedure, I understand it is so easy to solve problems with mathematical method. sometimes