Skip to content

Commit 7a2951f

Browse files
committed
Create Powers Of Two
1 parent 8f1f879 commit 7a2951f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Powers Of Two

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/***************************************************************************************
2+
* *
3+
* CODERBYTE BEGINNER CHALLENGE *
4+
* *
5+
* Powers of Two *
6+
* Using the JavaScript language, have the function PowersofTwo(num) take the num *
7+
* parameter being passed which will be an integer and return the string true if *
8+
* it's a power of two. If it's not return the string false. For example if the *
9+
* input is 16 then your program should return the string true but if the input is *
10+
* 22 then the output should be the string false *
11+
* *
12+
* SOLUTION *
13+
* To find if a number is a power of 2 you divide number by 2 repeatedly. *
14+
* If final number is a two then it is a power of 2. I will use a while loop to *
15+
* handle the repeated division by two. I will use modulus to determine if final *
16+
* number is two meaning we have a number that is a power of 2. *
17+
* *
18+
* Steps for solution *
19+
* 1) Initialize vars divis and newNum *
20+
* 2) Loop by dividing number by 2 and seeing if it is an even number *
21+
* 3) Test if last number is 2 meaning it is a power of 2 *
22+
* *
23+
***************************************************************************************/
24+
function PowersofTwo(num) {
25+
26+
var divis;
27+
var newNum;
28+
29+
divis = num % 2;
30+
newNum = num / 2;
31+
while ( divis === 0 && newNum !== 2) {
32+
divis = newNum % 2;
33+
newNum = newNum / 2;
34+
}
35+
36+
if (newNum === 2) {
37+
return true;
38+
}
39+
else {
40+
return false;
41+
}
42+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy