Skip to content

Instantly share code, notes, and snippets.

@erichsu
Created September 27, 2020 09:31
Show Gist options
  • Save erichsu/bb10f4011bcded90518aff56f06dee4c to your computer and use it in GitHub Desktop.
Save erichsu/bb10f4011bcded90518aff56f06dee4c to your computer and use it in GitHub Desktop.
Quiz 3: Contains 7s
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