-
Notifications
You must be signed in to change notification settings - Fork 0
/
isPowerOfTwo.js
55 lines (44 loc) · 1.29 KB
/
isPowerOfTwo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 2의 거듭 제곱 확인
function isPowerOfTwo(number) {
// 1 (2^0) is the smallest power of two.
if (number < 1) {
return false;
}
// Let's find out if we can divide the number by two
// many times without remainder.
let dividedNumber = number;
while (dividedNumber !== 1) {
if (dividedNumber % 2 !== 0) {
// For every case when remainder isn't zero we can say that this number
// couldn't be a result of power of two.
return false;
}
dividedNumber /= 2;
}
return true;
}
function isPowerOfTwoBitwise(number) {
// 1 (2^0) is the smallest power of two.
if (number < 1) {
return false;
}
/*
* Powers of two in binary look like this:
* 1: 0001
* 2: 0010
* 4: 0100
* 8: 1000
*
* Note that there is always exactly 1 bit set. The only exception is with a signed integer.
* e.g. An 8-bit signed integer with a value of -128 looks like:
* 10000000
*
* So after checking that the number is greater than zero, we can use a clever little bit
* hack to test that one and only one bit is set.
*/
return (number & (number - 1)) === 0;
}
function test() {
console.log(isPowerOfTwoBitwise(1024));
}
test();