-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse_Integer
48 lines (43 loc) · 1.19 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
/*
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
*/
class Solution {
public:
int reverse(int x) {
if (x==0) return 0;
int res=0;
while (x!=0)
{
res = 10*res + (x%10);
x = int(x/10);
}
return res;
}
};
REMARK:
1. I first considered the problem in a more complicated way: first convert it to a string, then use for loop to reverse the string, then convert it back to an integer. Moreover, the function itoa which convert an integer to an array is not standard and not provided on my compiler.
However, after I search the internet, the problem is supposed to be easy.
2. Detail: (-321)%10 = -1. Therefore, we don't need to check whether the x is positive or negative.
class Solution {
public:
int reverse(int x) {
if (x==0) return 0;
else if (x>0)
{
char buffer[256];
itoa(x,buffer,10);
int n;
for (n=0; n<256; ++n)
if (buffer[n]=='\0') break;
for (int i=0; i<n/2; ++i)
{
int temp = buffer[i];
buffer[i]=buffer[n-i-1];
}
return atoi(buffer);
}
}
};