CodeWar(JavaScript)---Perimeter of squares in a rectangle

Perimeter of squares in a rectangle

问题:

The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It’s easy to see that the sum of the perimeters of these squares is : 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80

Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing:

alternative text

#Hint: See Fibonacci sequence

#Ref: http://oeis.org/A000045

The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares.

perimeter(5)  should return 80
perimeter(7)  should return 216

NOTE: due to a misspelling in the reference solution for random tests, have an outer auxiliary function that calculates Fibonacci numbers, name this outer function fib. (More than 500 CW passed the kata so it is now impossible to change the random tests).
翻译(来自有道翻译):

这张图显示了6个正方形,它们的边长是1、1、2、3、5、8。很容易看出,这些正方形的周长之和是:4 * (1 + 1 + 2 + 3 + 5 + 8)= 4 * 20 = 80

当n + 1个正方形按图中所示的方式排列时,能否给出一个矩形中所有正方形的周长之和:

替代文本

提示:参见斐波那契数列

#裁判:http://oeis.org/A000045

函数周长为参数n,其中n + 1是正方形的数目(它们的编号从0到n),并返回所有正方形的总周长。

perimeter(5)  should return 80
perimeter(7)  should return 216

注意:由于在随机测试的参考解决方案中有一个拼写错误,有一个计算斐波那契数的外部辅助函数,将这个外部函数命名为fib。(超过500名CW通过了kata,所以现在不可能改变随机测试)。
个人解题代码:

//思路:初始化tmp为一个[1,1]的数组,for循环n次并计算相应的num
//每次循环将num加到sum当中最后输出sum*4
function perimeter(n) {
  var tmp = [1,1];
  var num = 0;
  var sum = 2;
  for(var i = 0 ; i < n-1 ; i++){
    num = tmp[i] + tmp[i+1];
    tmp.push(num);
    sum+=num
  }
  return sum*4
  
}

高亮回答:

function perimeter(n) {
  let arr = [1, 1];
  for(let i = 0; i < n - 1; i++) {
    arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
  }
  return 4 * arr.reduce((sum, num) => sum + num, 0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值