codewars-js练习
2021/3/16
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:
- current father’s age (years)
- 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>
本文介绍了两道Codewars JavaScript练习题的解决方法。第一题为计算金字塔层级,通过给定球的数量来确定金字塔的层数。第二题为计算父亲年龄是儿子年龄两倍的时间点。文中给出了具体的实现代码及测试案例。
225

被折叠的 条评论
为什么被折叠?



