Skip to content

Commit 8b9d497

Browse files
add problem 7 add test function
1 parent 40dd0da commit 8b9d497

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

C/1-50/7-Reverse-Integer.c

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Reverse digits of an integer.
3+
*
4+
* Example1: x = 123, return 321
5+
* Example2: x = -123, return -321
6+
* Created by supercoderhawk on 2017/7/23.
7+
*/
8+
9+
#include
10+
#include
11+
12+
int reverse(int x) {
13+
long long maxInt = (long) pow(2, 31), result = 0;
14+
int num = x, length = 0;
15+
while (num != 0) {
16+
num /= 10;
17+
length += 1;
18+
}
19+
num = x;
20+
for (int i = length - 1; i >= 0; i--) {
21+
result = result * 10 + (num % 10);
22+
num /= 10;
23+
}
24+
if (result > maxInt || result < -maxInt - 1)
25+
result = 0;
26+
27+
return (int) result;
28+
}
29+
30+
void testReverse() {
31+
printf("%d", reverse(123));
32+
printf("%d", reverse(-2147483648));
33+
}

0 commit comments

Comments
 (0)