Power of 3
Title description: Given an integer, write a function to determine whether it is a power of 3. If yes, return true; otherwise, return false.
If the integer n is a power of 3, it must satisfy: there is an integer x such that n == $3^{x}$
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/power-of-three/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Round Robin
First, if n is equal to 0, then return false directly.
If n is not equal to 0, the loop processing is performed, and the processing procedure is as follows:
- If n is not divisible by 3, return false directly;
- Otherwise, reset n to
n/3
, and then proceed to the next round of processing;- The condition for the end of the loop is that n is less than 3.
Finally, it is judged that if n is equal to 1, it returns true; otherwise, it returns false.
public class LeetCode_326 {
/**
* 循环
*
* @param n
* @return
*/
public static boolean isPowerOfThree(int n) {
// 如果n等于0,则直接返回false
if (n == 0) {
return false;
}
while (n >= 3) {
// 如果n不能被3整除,则直接返回false
if (n % 3 != 0) {
return false;
}
n = n / 3;
}
if (n == 1) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
System.out.println(isPowerOfThree(45));
}
}
[Daily Message] You can't be perfect, but you can be unique.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。