Created
September 27, 2020 09:31
-
-
Save erichsu/bb10f4011bcded90518aff56f06dee4c to your computer and use it in GitHub Desktop.
Quiz 3: Contains 7s
This file contains hidden or 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
import UIKit | |
import PlaygroundSupport | |
/* | |
Let g(N) be the count of numbers that contain a 7 when you write out all the numbers from 1 to N. | |
g(7) = 1 | |
g(20) = 2 | |
g(70) = 8 | |
g(100) = 19 | |
What is g(1000)? | |
Write a computer program to compute g(N) | |
*/ | |
func g(_ n: Int) -> Int { | |
var count = 0 | |
for i in (1...n) { | |
let text = String(i) | |
count += text.contains("7") ? 1 : 0 | |
} | |
return count | |
} | |
assert(g(7) == 1, "g(7) should be 1") | |
assert(g(20) == 2, "g(20) should be 2") | |
assert(g(70) == 8, "g(70) should be 8") | |
assert(g(100) == 19, "g(100) should be 19") | |
print("\(g(1000))") | |
// Ans = 271 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment