Check if Number is a Sum of Powers of Three

medium math ternary base conversion

Problem

Given an integer n, return true if n can be written as the sum of distinct powers of three (30, 31, 32, …), each used at most once. Otherwise return false.

Key fact: writing n in base 3 uses each power 3x a digit-many (0, 1, or 2) times. A sum of distinct powers means every base-3 digit must be 0 or 1 — so the answer is true exactly when no ternary digit is 2.

Inputn = 12
Outputtrue
12 = 31 + 32. In base 3, 12 = 110₃ — only 0s and 1s, so it works.

def checkPowersOfThree(n):
    # Strip n into base-3 digits from least significant up.
    while n > 0:
        if n % 3 == 2:      # a digit of 2 means 3^x used twice
            return False    # not a sum of distinct powers
        n //= 3             # drop this digit, move to next power
    return True             # every digit was 0 or 1
function checkPowersOfThree(n) {
  // Strip n into base-3 digits from least significant up.
  while (n > 0) {
    if (n % 3 === 2) {      // a digit of 2 means 3^x used twice
      return false;         // not a sum of distinct powers
    }
    n = Math.floor(n / 3);  // drop this digit, move to next power
  }
  return true;              // every digit was 0 or 1
}
boolean checkPowersOfThree(int n) {
    // Strip n into base-3 digits from least significant up.
    while (n > 0) {
        if (n % 3 == 2) {   // a digit of 2 means 3^x used twice
            return false;   // not a sum of distinct powers
        }
        n /= 3;             // drop this digit, move to next power
    }
    return true;            // every digit was 0 or 1
}
bool checkPowersOfThree(int n) {
    // Strip n into base-3 digits from least significant up.
    while (n > 0) {
        if (n % 3 == 2) {   // a digit of 2 means 3^x used twice
            return false;   // not a sum of distinct powers
        }
        n /= 3;             // drop this digit, move to next power
    }
    return true;            // every digit was 0 or 1
}
Time: O(log₃ n) Space: O(1)