326. Power of Three
Given an integer, write a function to determine if it is a power of three.
解題思路
這道題要求不用循環(huán)和遞歸困后。则酝。。伟叛。勃教。委乌。。荣回。(本來超水)
不過我們可以逆向考慮遭贸,3的k的冪一定能被3的n的冪整除(其中3的n的冪為范圍內(nèi)最大的power of 3).......(還是略水)
代碼
class Solution {
public:
bool isPowerOfThree(int n) {
return ( n>0 && 1162261467%n==0);
}
};
342. Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
解題思路
一看到這題還以為跟上面那題是一樣的,仔細(xì)一想不對(duì)啊心软,不能滿足上面關(guān)系的數(shù)還挺多的(比如8壕吹,32)。不過范圍內(nèi)4的k次冪確實(shí)不多删铃,那就打個(gè)表咯~
代碼
class Solution {
public:
bool isPowerOfFour(int num) {
switch(num){
case 1:
return true;
case 4:
return true;
case 16:
return true;
case 64:
return true;
case 256:
return true;
case 1024:
return true;
case 4096:
return true;
case 16384:
return true;
case 65536:
return true;
case 262144:
return true;
case 1048576:
return true;
case 4194304:
return true;
case 16777216:
return true;
case 67108864:
return true;
case 268435456:
return true;
case 1073741824:
return true;
dafault:
return false;
}
return false;
}
};
這段代碼擊敗了100%的代碼耳贬,打表大法好啊