【codewars-18】弹跳球

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.

Examples:

- h = 3, bounce = 0.66, window = 1.5, result is 3

- h = 3, bounce = 1, window = 1.5, result is -1 

分析

以一次高于window的下落和随后的反弹作为一次循环. 每次循环更新一次cur, 作为一次下落+回弹后那一瞬间的高度.
这样一次循环至少增加一次count, 因为高于window的下落至少会贡献一次; 只要反弹后的高度> window,那么意味着两件事情:

  1. count在本次循环中要增加2
  2. 循环还会有下一次.

反之, 若反弹后的高度cur < window, 则有:

  1. count只会增加一次.
  2. 这将是最后一次循环.
class Bouncingball
{
public:
    static int bouncingBall(double h, double bounce, double window){
      if(h <= 0 || bounce <=0 || bounce >=1 || window >= h){
        return -1;
      } 
     int count{0};
     double cur{h};
      while(cur > window) {
        cur = cur*bounce ;
        count += (cur>window)? 2 :1 ;
      }
      return count;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值