forked from Dungeonlx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalin_num.cpp
98 lines (79 loc) · 1.61 KB
/
palin_num.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int m_pos(const char* nptr, int c)
{
int pos = 0;
while (*nptr)
{
if (*nptr == c)
return pos;
nptr++;
pos++;
}
return pos;
}
int m_atoi(const char* nptr)
{
bool isNegative = false;
int i = 0;
int mul = strlen(nptr) - 1;
if (index(nptr, '.'))
mul = m_pos(nptr, '.') - 1;
if (*nptr == '-')
isNegative = true;
else
i += (*nptr - 48) * pow(10, mul);
nptr++;
mul--;
while (*nptr)
{
if (*nptr == '.')
break;
i += (*nptr - 48) * pow(10, mul);
nptr++;
mul--;
}
if (isNegative)
return 0 - i;
return i;
}
unsigned int reverse(unsigned int num)
{
unsigned int rev = 0;
while (num)
{
rev = rev * 10 + num % 10;
num /= 10;
}
return rev;
}
bool isPalindrome(int x)
{
if (x < 0) return false;
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int l = x / div;
int r = x % 10;
if (l != r) return false;
// remove l and r
// l -------------- r
x = (x % div) / 10;
// remove l and r 2 digits
div /= 100;
}
return true;
}
int main(int argc, char* argv[])
{
unsigned int num = 616;
printf("%d\n", argv[1] ? m_atoi(argv[1]) : num);
printf("%d\n", argv[1] ? atoi(argv[1]) : num);
printf("%d\n", argv[1] ? reverse(atoi(argv[1])) : reverse(num));
printf("%d\n", argv[1] ? isPalindrome(atoi(argv[1])) : isPalindrome(num));
return 0;
}