描述
A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.
He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).
His mother looks out of a window 1.5 meters from the ground.
How many times will the mother see the ball pass in front of her window (including when it’s falling and bouncing?
Three conditions must be met for a valid experiment:
Float parameter “h” in meters must be greater than 0
Float parameter “bounce” must be greater than 0 and less than 1
Float parameter “window” must be less than h.
If all three conditions above are fulfilled, return a positive integer, otherwise return -1.
Note:
The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.
分析
方法1:递归实现。每次球弹起到最高点,之后的过程可以看做一个起始高度减少的流程相同的问题。终止条件为起始高度低于窗户高度。
方法2:递推实现。
实现
方法1:
func BouncingBall(h, bounce, window float64) int {
if h <= 0 || bounce <= 0 || bounce >= 1 || window >= h { return -1 }
return 2 + BouncingBall((h * bounce), bounce, window)
}
方法2:
func BouncingBall(h, bounce, window float64) int {
if h <= 0 || bounce <= 0 || bounce >= 1 || window >= h { return -1 }
sum := 0
for ; h * bounce > window; h *= bounce { sum += 2 }
return sum + 1
}