Skip to content

Commit ebc1f0f

Browse files
use base conversion to solve power of three
1 parent a87a7d8 commit ebc1f0f

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

EASY/src/easy/PowerOfThree.java

+8
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@
1111
*/
1212

1313
public class PowerOfThree {
14+
//then I turned to the Editorial solution, it's pretty elegant to use base conversion which can be easily extended to any radix k
15+
//Idea: for a number in base 10, if it's power of 10, then it must be in this format: 10, 100, 1000... with a leading one and all trailing zeros
16+
//similarly, if a number is power of 3, then in its base 3 format, it must be in this format as well: 10, 100, 1000, 1000...
17+
//some Java built-in function could help us along the way:
18+
public boolean isPowerOfThree_base_conversion(int n){
19+
return Integer.toString(n, n).matches("^10*$");
20+
}
21+
1422
//it turns out they're using a trick to solve this question without using a loop: find the max possible integer that is a power of 3, then do modulor with this number
1523
public boolean isPowerOfThree_without_loop(int n) {
1624
return (n > 0 && 1162261467 % n == 0);

0 commit comments

Comments
 (0)