codewars练习(javascript)-2021/3/16

本文介绍了两道Codewars JavaScript练习题的解决方法。第一题为计算金字塔层级,通过给定球的数量来确定金字塔的层数。第二题为计算父亲年龄是儿子年龄两倍的时间点。文中给出了具体的实现代码及测试案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

codewars-js练习

2021/3/16

github 地址

my github地址,上面有做的习题记录,不断更新…

【1】<7kyu>【Billiards pyramid】

example

     *
   *   *
 *   *    *
       
pyramid(1) == 1

pyramid(3) == 2

pyramid(6) == 3

pyramid(10) == 4

pyramid(15) == 5

思路

假设 pyramid(balls) == n;则满足 n 2 + n 2 = b a l l s \frac{n^2+n}{2}= balls 2n2+n=balls,因此现在反求出n即可。

solution

<script type="text/javascript">
    function pyramid(balls) {
        // console.log(balls);
        var deta = 1 + 8*balls;
        var result = (-1+Math.sqrt(deta,2))/2;
        return Math.floor(result);
    }

    // 验证
    console.log(pyramid(21));//6
    console.log(pyramid(10));//4
</script>
【2】<8kyu>【Twice as old】

Your function takes two arguments:

  1. current father’s age (years)
  2. current age of his son (years)

Сalculate how many years ago the father was twice as old as his son (or in how many years he will be twice as old).

example

(36,7)//22
(55,30)//5
(29,0)//29

solution

<script type="text/javascript">
    function twiceAsOld(dadYearsOld, sonYearsOld) {
        // console.log(dadYearsOld,sonYearsOld)
        return Math.abs(sonYearsOld * 2 - dadYearsOld)
    }

    // 验证
    console.log(twiceAsOld(36,7));// 22
    console.log(twiceAsOld(42,21));// 0
    console.log(twiceAsOld(29,0));// 29
    console.log(twiceAsOld(55,30));//5
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值