Skip to main content
Back to problems
#1780
Medium Algorithms

Check if number is a sum of powers of three

Math
79.4% acceptance
Feb 25, 2026
1668
67
Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false. An integer y is a power of three if there exists an integer x such that y == 3^x.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn check_powers_of_three(n: i32) -> bool {
    let mut n = n;
    while n > 0 {
      if n % 3 == 2 { return false; }
      n /= 3;
    }
    true
  }
}