Skip to content

Instantly share code, notes, and snippets.

@mayrop
Last active January 17, 2020 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayrop/dbad266651ff7f823debc0ee0ff4b935 to your computer and use it in GitHub Desktop.
Save mayrop/dbad266651ff7f823debc0ee0ff4b935 to your computer and use it in GitHub Desktop.
Given a number n, find the sum of all n-digit palindromes.
# Interview Question of the Week: Jan 13, 2020
# 126 of rendezvous with cassidoo
# https://cassidoo.co/newsletter/
# Given a number n, find the sum of all n-digit palindromes.
# >> nPalindromes(2)
# >> 495 // 11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99
# Removing exponential notation
options(scipen=999)
nPalindrome <- function(n) {
# returning 0 by default
if (n == 0 | !is.numeric(n)) {
return(0)
}
if (n == 1) {
return(sum(1:9))
}
# this is how many inner loops we need to do
# to get the sum of inner numbers
times <- ceiling((n-2) / 2)
# this will be the base number that will the the numbers in the extremes
# i.e. for n = 3, 101, for n = 4, 1001, for n = 5, 10001
base <- 10 ^ (n-1) + 1
# outer sum will be...
outer_sum <- base * sum(1:9) * 10 ^ times
# no need to do any inner loop if we're giving n = 2
if (!times) {
return(outer_sum)
}
inner_sum <- 0
is_n_odd <- (n / 2) %% 1 != 0
for (i in 1:times) {
# how many combinations do we have...
# 9 (since when the first number is 0 it doesn't count)
n_comb <- 9 * 10 ^ (times-1)
# we're adding 10 exponentiated to the i
multiplier <- 10 ^ i
# but don't do that if if it's last number to add AND
# length of n is odd
if (i == times & is_n_odd) {
multiplier <- 0
}
inner_sum <- inner_sum + sum(1:9) * n_comb * (10 ^ (n - 1 - i) + multiplier)
}
return(outer_sum + inner_sum)
}
sapply(1:10, function(i) {
print(paste(i, "=>", nPalindrome(i)))
})
# [1] "1 => 45"
# [1] "2 => 495"
# [1] "3 => 49500"
# [1] "4 => 495000"
# [1] "5 => 49500000"
# [1] "6 => 495000000"
# [1] "7 => 49500000000"
# [1] "8 => 495000000000"
# [1] "9 => 49500000000000"
# [1] "10 => 495000000000000"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment