codewars练习(javascript)

编程入门 行业动态 更新时间:2024-10-06 20:38:00

<a href=https://www.elefans.com/category/jswz/34/1651108.html style=codewars练习(javascript)"/>

codewars练习(javascript)

文章目录

    • codewars-js练习
      • 2021/2/3
        • github 地址
        • 【1】<7kyu>【Gauß needs help! (Sums of a lot of numbers).】
        • 【2】<7kyu>【Sum of odd numbers】

codewars-js练习

2021/2/3

github 地址

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

【1】<7kyu>【Gauß needs help! (Sums of a lot of numbers).】

求和

example

f(n=100) // returns 5050 
f('n')//false
f(3.14)// false, "n must be an integer"
f(-10)//false, "a positive value of n is required
f(0)// false, "a value of n greater than 0 is required"

solution

<script type="text/javascript">function f(n){console.log(n);if(typeof n == 'number' && n % 1 ==0 && n > 0){var sum =0;for(var i=0;i<=n;i++){sum +=i;}return sum;}return false;	}// 验证console.log(f(100));//5050console.log(f('n'));//fasleconsole.log(f(3.14));//false</script>
【2】<7kyu>【Sum of odd numbers】

Given the triangle of consecutive odd numbers:

             13     57     9    1113    15    17    19
21    23    25    27    29
...

Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:

example

rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
rowSumOddNumbers(42);//74088

思路

n第一个数该行总数最后一个数
1111
2325
37311
413419
521529
n(n-1)+1 (n>=2)n(n-1)+1+(n-1)2=(n-1)(n+2)+1

根据n确定第一个数和该行最后一个数,从而计算。

solution

<script type="text/javascript">function rowSumOddNumbers(n) {// console.log(n);var one = n * (n-1) + 1;var last = (n-1) * (n+2) + 1;// console.log(one)var sum = 0;for(var i=one;i<=last;i=i+2){sum +=i;}return sum;}// 验证console.log(rowSumOddNumbers(1)); // 1console.log(rowSumOddNumbers(2)); // 3 + 5 = 8console.log(rowSumOddNumbers(42));//74088</script>

以上为自己思路供大家参考,可能有更优的思路。

更多推荐

codewars练习(javascript)

本文发布于:2024-02-25 08:15:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1698340.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:codewars   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!