I recently came across this coding challenge - The Unlucky number 13. (The last problem in the section)
Problem Statement:
Write a program to calculate the total number of strings that are made of exactly N characters. None of the strings can have "13" as a substring. The strings may contain any integer from 0-9, repeated any number of times.
Input: N is taken as input where 0<= N <= 1000000009.
Output: The output should be the answer modulo 1000000009.
My Solution:
I tried to solve it using a simple equation I came up with.
ans = 10^n - ((10^(n-2)) * (n-1))
Subtracting the possibilities with 13 as substring from the total number of possibilities.
I wrote the code in Swift. It works when N is small. But I get a runtime error on submission (probably when N is large).
Here is my code:
let input = Int(readLine()!)
if let n = input as? Int{
var ans = getPowerOfTen(n)
ans = ans - getPowerOfTen(n-2) * (n - 1)
print(ans % 1000000009)
}
// Did not import any library to calculate the power
func getPowerOfTen(_ num: Int)->Int{
var ans = 1
var n = num
while(n > 0){
ans = ans * 10
n = n - 1
}
return ans
}
I was hoping to get help for two questions.
Could you help me find the run time issue?
This is the screenshot of the runtime error I get from the site.
Could there be a better way to solve this?
I found this in Array & Strings problem section. I did not use any array though. I think this equation works.