給定一個整數,寫一個函數來判斷它是否是 3 的冪次方。
示例 1:
輸入: 27
輸出: true
示例 2:
輸入: 0
輸出: false
示例 3:
輸入: 9
輸出: true
示例 4:
輸入: 45
輸出: false
進階:
你能不使用循環或者遞歸來完成本題嗎?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/power-of-three
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
/**
給定一個整數,寫一個函數來判斷它是否是 3 的冪次方
*/
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
/**
思路一:通過取餘+除法操作
思路二:換底公式若n是3的冪,那麼log3(n)一定是個整數,由換底公式可以的得到log3(n) = log10(n) / log10(3),只需要判斷log3(n)是不是整數即可
C語言中,有兩個log函數,分別爲log10和log函數
*/
bool isPowerOfThree1(int n){
if(n ==0 ){
return false;
}
int tmp = n;
while(tmp!=1){
if(tmp%3 == 0){
tmp = tmp/3;
}else{
return false;
}
}
return true;
}
bool isPowerOfThree(int n){
double result = log10(n)/log10(3);
if(result -(int)result == 0){
return true;
}else
return false;
// (result==0)?return true:return false;
}
int main(){
int a;
scanf("%d",&a);
bool result = isPowerOfThree(a);
printf("%d",result);
return 0;
}