1780. Check if Number is a Sum of Powers of Three LeetCode Solution

In this guide, you will get 1780. Check if Number is a Sum of Powers of Three LeetCode Solution with the best time and space complexity. The solution to Check if Number is a Sum of Powers of Three problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Check if Number is a Sum of Powers of Three solution in C++
  4. Check if Number is a Sum of Powers of Three solution in Java
  5. Check if Number is a Sum of Powers of Three solution in Python
  6. Additional Resources
1780. Check if Number is a Sum of Powers of Three LeetCode Solution image

Problem Statement of Check if Number is a Sum of Powers of Three

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 == 3x.

Example 1:

Input: n = 12
Output: true
Explanation: 12 = 31 + 32

Example 2:

Input: n = 91
Output: true
Explanation: 91 = 30 + 32 + 34

Example 3:

Input: n = 21
Output: false

Constraints:

1 <= n <= 107

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

1780. Check if Number is a Sum of Powers of Three LeetCode Solution in C++

class Solution {
 public:
  bool checkPowersOfThree(int n) {
    while (n > 1) {
      const int r = n % 3;
      if (r == 2)
        return false;
      n /= 3;
    }

    return true;
  }
};
/* code provided by PROGIEZ */

1780. Check if Number is a Sum of Powers of Three LeetCode Solution in Java

class Solution {
  public boolean checkPowersOfThree(int n) {
    while (n > 1) {
      const int r = n % 3;
      if (r == 2)
        return false;
      n /= 3;
    }

    return true;
  }
}
// code provided by PROGIEZ

1780. Check if Number is a Sum of Powers of Three LeetCode Solution in Python

class Solution:
  def checkPowersOfThree(self, n: int) -> bool:
    while n > 1:
      n, r = divmod(n, 3)
      if r == 2:
        return False
    return True
# code by PROGIEZ

Additional Resources

See also  3120. Count the Number of Special Characters I LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.