Powers of 2

Instructions:
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,…


This content originally appeared on DEV Community and was authored by Madalina Pastiu

Instructions:
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]

Thoughts:

  1. I do create an array inside the function with n length. const arr = new Array(n); 2.Using a for loop it gives me the ability to loop until n (including n in this case) and raise 2 to the power of i until i=n. 3.In every iteration of the loop, I add the el to the newArr. newArr.push(el);

Solution:
function powersOfTwo(n){
const arr = new Array(n);
let newArr = [];
for (let i = 0; i <= n; i++) {
const el = Math.pow(2, i);
newArr.push(el);
}
return newArr;
}

This is a CodeWars Challenge of 8kyu Rank (https://www.codewars.com/kata/57a083a57cb1f31db7000028/train/javascript)


This content originally appeared on DEV Community and was authored by Madalina Pastiu


Print Share Comment Cite Upload Translate Updates
APA

Madalina Pastiu | Sciencx (2025-04-19T21:41:00+00:00) Powers of 2. Retrieved from https://www.scien.cx/2025/04/19/powers-of-2/

MLA
" » Powers of 2." Madalina Pastiu | Sciencx - Saturday April 19, 2025, https://www.scien.cx/2025/04/19/powers-of-2/
HARVARD
Madalina Pastiu | Sciencx Saturday April 19, 2025 » Powers of 2., viewed ,<https://www.scien.cx/2025/04/19/powers-of-2/>
VANCOUVER
Madalina Pastiu | Sciencx - » Powers of 2. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/04/19/powers-of-2/
CHICAGO
" » Powers of 2." Madalina Pastiu | Sciencx - Accessed . https://www.scien.cx/2025/04/19/powers-of-2/
IEEE
" » Powers of 2." Madalina Pastiu | Sciencx [Online]. Available: https://www.scien.cx/2025/04/19/powers-of-2/. [Accessed: ]
rf:citation
» Powers of 2 | Madalina Pastiu | Sciencx | https://www.scien.cx/2025/04/19/powers-of-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.