Post

342 Power Of Four

342 Power Of Four

Power of Four image

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4x.

 

Example 1:

1
2
3
**Input:** n = 16
**Output:** true

Example 2:

1
2
3
**Input:** n = 5
**Output:** false

Example 3:

1
2
3
**Input:** n = 1
**Output:** true

 

Constraints:

1
-231 <= n <= 231 - 1

 

Follow up: Could you solve it without loops/recursion?

1
2
3
4
5
6
7
8
9
10
11
12
13
14

impl Solution {
    pub fn is_power_of_four(n: i32) -> bool {
       // bin of 2 is 10, 100 is 4, 1000 is 8, 10000 is 16
       // so 100 ^ 011 is 0 for 2, onlt check extra if n % 3 == 0
       return (n & (n -1)) == 0 && n % 3 == 1

      
    }
}



This post is licensed under CC BY 4.0 by the author.