[Codility/Swift] lesson 3 : FrogJmp
Task description
- Notice: X, Y and D are integers within the range [1..1,000,000,000]
Solution
At first, I used a while loop to solve this problem, but it resulted in a timeout. Since the input can be as large as 1,000,000,000, we cannot use an O(N) algorithm here.
Instead, we need to find the rule and derive the equation to solve the problem efficiently.
import Foundation
import Glibc
public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
let rst: Int = Int((Y - X) / D)
if Int((Y - X) % D) == 0 {
return rst
} else {
return rst + 1
}
}