Powers of 2

Lee·2022년 7월 25일

Algorithm

목록 보기
58/92
post-thumbnail

❓ Powers of 2

Q. Complete the function that takes a non-negative integer n as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to n ( inclusive ).

Examples
n = 0 ==> [1] # [2^0]
n = 1 ==> [1, 2] # [2^0, 2^1]
n = 2 ==> [1, 2, 4] # [2^0, 2^1, 2^2]

✔ Solution

//#my solution
function powersOfTwo(n){
  var myArray = [];
  for (let i=0; i<=n; i++){
    myArray.push(2**i);
  }
  return myArray
}

//other solution
function powersOfTwo(n){
  var result = [];
  for (var i = 0; i <= n; i++) {
    result.push(Math.pow(2, i));
  }
  return result;
}
profile
Lee

0개의 댓글