Skip to content

Instantly share code, notes, and snippets.

@brianvp
Created January 22, 2016 03:38
Show Gist options
  • Save brianvp/bf73f095c7dde75df1a9 to your computer and use it in GitHub Desktop.
Save brianvp/bf73f095c7dde75df1a9 to your computer and use it in GitHub Desktop.
backward_and_forward
# 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])
@brianvp
Copy link
Author

brianvp commented Jan 22, 2016

answer(42) -> Base 4
answer(0) - > base 2

@brianvp
Copy link
Author

brianvp commented Jan 22, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment