Skip to content

1780. Check if Number is a Sum of Powers of Three 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  bool checkPowersOfThree(int n) {
    while (n > 1) {
      const int r = n % 3;
      if (r == 2)
        return false;
      n /= 3;
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public boolean checkPowersOfThree(int n) {
    while (n > 1) {
      const int r = n % 3;
      if (r == 2)
        return false;
      n /= 3;
    }

    return true;
  }
}
1
2
3
4
5
6
7
class Solution:
  def checkPowersOfThree(self, n: int) -> bool:
    while n > 1:
      n, r = divmod(n, 3)
      if r == 2:
        return False
    return True