Post

326 Power Of Three

326 Power Of Three

Power of Three image

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

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

 

Example 1:

1
2
3
4
5
**Input:** n = 27
**Output:** true
**Explanation:** 27 = 33

Example 2:

1
2
3
4
5
**Input:** n = 0
**Output:** false
**Explanation:** There is no x where 3x = 0.

Example 3:

1
2
3
4
5
**Input:** n = -1
**Output:** false
**Explanation:** There is no x where 3x = (-1).

 

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
15
16
17
18
19
20

impl Solution {
    pub fn is_power_of_three(n: i32) -> bool {

        if n == 1 {
            return true;
        }
        if n < 1 {
            return false;
        }
        if n % 3 != 0 {
            return false;
        }
        return Self::is_power_of_three(n / 3)
    }
}



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