Created
January 22, 2016 03:38
-
-
Save brianvp/bf73f095c7dde75df1a9 to your computer and use it in GitHub Desktop.
backward_and_forward
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# write a function answer(n) which returns the smallest positive integer base b, at least 2, | |
# in which the integer n is a palindrome. The input n will satisfy "0 <= n <= 1000." | |
def answer(n): | |
base = 1 | |
num1 = -1 | |
num2 = 0 | |
while num1 != num2: | |
base = base + 1 | |
num1 = int(numberToBase(str(n), base)) | |
num2 = int(str(num1)[::-1]) | |
return base | |
def numberToBase(n, b): | |
n = int(n, 0) | |
if n == 0: | |
return "0" | |
digits = [] | |
while n: | |
digits.append(int(n % b)) | |
n /= b | |
return ''.join(str(x) for x in digits[::-1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
answer(42) -> Base 4
answer(0) - > base 2