|
| 1 | +packageeasy; |
| 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 | +publicclassPowerOfThree { |
| 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 | +publicbooleanisPowerOfThree_without_loop(intn) { |
| 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 | +publicbooleanisPowerOfThree(intn) { |
| 21 | +if(n <3 &&n !=1)returnfalse; |
| 22 | +while(n !=1){ |
| 23 | +if(n%3 !=0)returnfalse; |
| 24 | +n /=3; |
| 25 | + } |
| 26 | +returntrue; |
| 27 | + } |
| 28 | + |
| 29 | +publicstaticvoidmain(String...strings){ |
| 30 | +PowerOfThreetest =newPowerOfThree(); |
| 31 | +System.out.println(test.isPowerOfThree(12)); |
| 32 | + |
| 33 | +//find the max integer that is power of 3 |
| 34 | +intmaxPowerOf3_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 | +} |