Last active
January 13, 2020 18:02
-
-
Save les-peters/97f5e64defad6582a6f5e0ed336c1cd3 to your computer and use it in GitHub Desktop.
Cassidoo IQofW 2020-01-13
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
# cassidoo Interview Question of the Week: January 13, 2020 | |
# Given a number n, find the sum of all n-digit palindromes. | |
# Example: | |
# > nPalindromes(2) | |
# > 495 // 11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99 | |
def nPalindromes(length): | |
sum = 0 | |
if length == 0: | |
return sum | |
elif length == 1: | |
for digit in range(1,10): | |
sum += digit | |
return sum | |
elif length == 2: | |
for digit in range(1,10): | |
sum += (digit * 10) + digit | |
return sum | |
else: | |
nP1 = nPalindromes(1) | |
sum = nP1 * (10 ** (length - 1)) * (10 ** int(length / 2)) | |
sum += nPalindromes(length - 2) * 90 | |
sum += nP1 * (10 ** (int(length / 2))) | |
return sum | |
for digit in range(2,10): | |
print("sum of " + str(digit) + "-digit palindrome numbers = " + str(nPalindromes(digit))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment