版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82904980
Given an integer, write a function to determine if it is a power of three.
挑战
Could you do it without using any loop / recursion?
解题思路1:
对于小于0的数,肯定不是3的幂次方。反复除以3,最终得到的数字肯定是1,若除的中间有除不尽的情况,则不是3的幂次方。
public class Solution {
/**
* @param n: an integer
* @return: if n is a power of three
*/
public boolean isPowerOfThree(int n) {
// Write your code here
if(n <= 0)
return false;
while(n != 1){
if(n%3 != 0)
return false;
n /= 3;
}
return true;
}
}
解题思路2:
挑战要求不用循环或递归,那么有一个投机取巧的方法,由于输入是int,正数范围是0-2^31,在此范围中允许的最大的3的次方数为3^19,那么我们只要看这个数能否被n整除即可。
public class Solution {
/**
* @param n: an integer
* @return: if n is a power of three
*/
public boolean isPowerOfThree(int n) {
// Write your code here
return (n>0 && Math.pow(3,19)%n==0);
}
}