Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita87a7d8

Browse files
power of three
1 parentc712926 commita87a7d8

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎EASY/src/easy/PowerOfThree.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp