본문 바로가기
Happly Coding/CodeWars

[CodeWars] 8kyu#4 - Square(n) Sum

by Hello Do. 2016. 5. 28.

[CodeWars] 8kyu#4 - Square(n) Sum


■ Description:

Complete the squareSum method so that it squares each number passed into it and then sums the results together.


For example:

squareSum([1, 2, 2]); // should return 9


■ Qustion:

function squareSum(numbers){


}


■ My Solution:

1
2
3
4
5
6
7
function squareSum(numbers){
    var a = numbers[0]+numbers[1];
    var b = numbers[2];
    var powReturn =0;
    powReturn = Math.pow(a,b);
    return powReturn;
}
cs

주어진 1, 2, 2를 활용해서 9로 만들어라. 나는 (1+2) 2승으로 생각해서 풀었다.

실행해보면 결과는 나오는데, CodeWars에서 실행해 보면 자꾸 오류..ㅠㅠ

ERROR : squareSum did not return a value , 이유를 모르겠다.


■ Best  Solution 1:

처음보는 reduce 지금도 살짝 이해가...;;


1
2
3
4
5
function squareSum(numbers){
  return numbers.reduce(function(sum, n){
    return (n*n) + sum;
  }, 0)
}
cs



■ Best  Solution 2:

이게 딱 내 수준!! 그런데 다른 문제 풀이를 보면 아래처럼 배열 풀었더라.

배열의 수를 하나씩 꺼내서 제곱해서 더하는 식..


1
2
3
4
5
6
7
8
9
10
function squareSum(numbers)
  var totalSum = 0;
  for (i=0;i<numbers.length;i++)
  {
    totalSum += Math.pow(numbers[i], 2);
  }
  return totalSum;
}
 
cs