Check if Number is a Sum of Powers of Three LeetCode solution in Java

1
class Solution {
2
public boolean checkPowersOfThree(int n) {
3
// max power of 3
4
int maxPower = (int) (Math.log(n) / Math.log(3));
5

6
// save all the power of 3 from 0 to maxPower
7
// 3^0, 3^1, 3^2 .... 3^maxPower
8
int[] threePower = new int[maxPower + 1];
9
threePower[0] = 1;
10
for (int i = 1; i <= maxPower; i++) {
11
threePower[i] = threePower[i - 1] * 3;
12
}
13

14
// Intuition
15
// if we subtract n with every power of 3
16
// at the end if n is zero, then it is sum of power 3
17

18
// subtract n with power of 3,
19
// if n is graeter than power
20
for (int i = maxPower; i >= 0; i--) {
21
// n is greater/equal to power 3
22
if (n >= threePower[i]) {
23
n -= threePower[i];
24
}
25
}
26

27
return n == 0;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0