-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathispalindrome.cpp
More file actions
65 lines (53 loc) · 1.49 KB
/
ispalindrome.cpp
File metadata and controls
65 lines (53 loc) · 1.49 KB
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
Credit : https://github.com/haoel/leetcode/
#include <stdio.h>
class Solution {
public:
bool isPalindrome(int x) {
// Negative numbers are not considered to be palindromes.
if (x<0) {
return false;
}
int powersOfTen=1;
for (powersOfTen=1; (x/powersOfTen) >= 10; powersOfTen*=10 );
while (x != 0 ) {
int left = x / powersOfTen;
int right = x % 10;
if(left!=right){
return false;
}
// x % powersOfTen gives all digits minus most significant
// x / 10 takes away the least significant.
// Cheeky way of doing it.
x = (x%powersOfTen) / 10;
// As the number got trimmed down
powersOfTen /= 100;
}
return true;
}
bool isPalindrome2(int x) {
return (x>=0 && x == reverse(x));
}
private:
// Reverse string method
// Has problem with overflow and underflow cases.
int reverse(int x) {
int y=0;
int n;
while( x!=0 ){
n = x%10;
//Checking the over/underflow.
//Actually, it should be y>(INT_MAX-n)/10, but n/10 is 0, so omit it.
//if (y > INT_MAX/10 || y < INT_MIN/10)
//return 0
y = y*10 + n;
x /= 10;
}
return y;
}
};
int main()
{
Solution s;
printf("%d is %d\n", 5, s.isPalindrome(5) );
printf("%d is %d\n", 12000001, s.isPalindrome(12000021) );
}