forked from jeantimex/javascript-problems-and-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpower-of-four.js
44 lines (40 loc) · 825 Bytes
/
power-of-four.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
/**
* Power of Four
*
* Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
*
* Example 1:
*
* Input: 16
* Output: true
*
* Example 2:
*
* Input: 5
* Output: false
* Follow up: Could you solve it without loops/recursion?
*/
/**
* @param {number} num
* @return {boolean}
*/
const isPowerOfFour = num => {
// 0x55555555 is to get rid of those power of 2 but not power of 4
// so that the single 1 bit always appears at the odd position
return num > 0 && (num & (num - 1)) === 0 && (num & 0x55555555) !== 0;
};
/**
* Solution I: Using loops
*
* @param {number} num
* @return {boolean}
*/
const isPowerOfFour_I = num => {
if (num > 1) {
while (num % 4 === 0) {
num /= 4;
}
}
return num === 1;
};
export { isPowerOfFour, isPowerOfFour_I };