[LeetCode] Check if Number is a Sum of Powers of Three

1780. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool checkPowersOfThree(int n) {
int lg3 = log(n) / log(3);
while(n) {
int p = pow(3,lg3);
if(n >= p) {
n -= p;
if(n >= p) return false;
}
lg3--;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/04/PS/LeetCode/check-if-number-is-a-sum-of-powers-of-three/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.