-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy path0342_power_of_four_(easy).js
More file actions
46 lines (42 loc) · 885 Bytes
/
Copy path0342_power_of_four_(easy).js
File metadata and controls
46 lines (42 loc) · 885 Bytes
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
/**
* 342. Power of Four
*
* https://leetcode.com/problems/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 };