Skip to content

Commit 421a2ff

Browse files
committed
EPI: is number palindromic (CPP/Py)
1 parent 17dfe95 commit 421a2ff

File tree

3 files changed

+38
-6
lines changed

3 files changed

+38
-6
lines changed

elements-of-programming-interviews/cpp/is_number_palindromic.cc

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
11
#include "test_framework/generic_test.h"
22
bool IsPalindromeNumber(int x) {
3-
// TODO - you fill in here.
4-
return true;
3+
if (x < 0) {
4+
return false;
5+
}
6+
7+
int original = x;
8+
int revX = 0;
9+
while (x) {
10+
revX *= 10;
11+
revX += x % 10;
12+
x /= 10;
13+
}
14+
15+
return original == revX;
516
}
617

718
int main(int argc, char* argv[]) {

elements-of-programming-interviews/problem_mapping.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,15 +128,15 @@ problem_mapping = {
128128
},
129129
"4.09 Check if a decimal integer is a palindrome": {
130130
"C++: is_number_palindromic.cc": {
131-
"passed": 0,
131+
"passed": 20000,
132132
"total": 20000
133133
},
134134
"Java: IsNumberPalindromic.java": {
135135
"passed": 0,
136136
"total": 20000
137137
},
138138
"Python: is_number_palindromic.py": {
139-
"passed": 0,
139+
"passed": 20000,
140140
"total": 20000
141141
}
142142
},

elements-of-programming-interviews/python/is_number_palindromic.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,30 @@
11
from test_framework import generic_test
22

33

4+
# Palindrome reads forward and backward the same way,
5+
# so just reverse and compare; can do this a few ways.
6+
7+
def is_palindrome_number_simple(x: int) -> bool:
8+
if x < 0:
9+
return False
10+
return str(x)[::-1] == str(x)
11+
12+
413
def is_palindrome_number(x: int) -> bool:
5-
# TODO - you fill in here.
6-
return True
14+
"""
15+
If the interviewer says "no conversion to string",
16+
then just compute the reversed decimal value and
17+
compare to the original.
18+
"""
19+
if x < 0:
20+
return False
21+
original = x
22+
rev_x = 0
23+
while (x):
24+
rev_x *= 10
25+
rev_x += x % 10
26+
x = x//10
27+
return original == rev_x
728

829

930
if __name__ == '__main__':

0 commit comments

Comments
 (0)