Skip to content

Commit a87a7d8

Browse files
power of three
1 parent c712926 commit a87a7d8

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

EASY/src/easy/PowerOfThree.java

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package easy;
2+
/**326. Power of Three QuestionEditorial Solution My Submissions
3+
Total Accepted: 57555
4+
Total Submissions: 151383
5+
Difficulty: Easy
6+
Given an integer, write a function to determine if it is a power of three.
7+
8+
Follow up:
9+
Could you do it without using any loop / recursion?
10+
11+
*/
12+
13+
public class PowerOfThree {
14+
//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
15+
public boolean isPowerOfThree_without_loop(int n) {
16+
return (n > 0 && 1162261467 % n == 0);
17+
}
18+
19+
//I'm not able to think of a method that has no loop to do it, use regular method to solve it first
20+
public boolean isPowerOfThree(int n) {
21+
if(n < 3 && n != 1) return false;
22+
while(n != 1){
23+
if(n%3 != 0) return false;
24+
n /= 3;
25+
}
26+
return true;
27+
}
28+
29+
public static void main(String...strings){
30+
PowerOfThree test = new PowerOfThree();
31+
System.out.println(test.isPowerOfThree(12));
32+
33+
//find the max integer that is power of 3
34+
int maxPowerOf3_one_step_further = 3, maxPowerOf3 = 0;
35+
while(maxPowerOf3_one_step_further >= 0){
36+
maxPowerOf3_one_step_further = (int) maxPowerOf3_one_step_further*3;
37+
if(maxPowerOf3_one_step_further > 0) maxPowerOf3 = maxPowerOf3_one_step_further;
38+
System.out.println("maxPowerOf3 is: " + maxPowerOf3);
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)