文章目錄
326 Power of Three
Problem Description
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
Follow up:
Could you do it without using any loop / recursion?
Solution Method
bool isPowerOfThree(int n)
{
switch (n)
{
case 1:
case 3:
case 9:
case 27:
case 81:
case 243:
case 729:
case 2187:
case 6561:
case 19683:
case 59049:
case 177147:
case 531441:
case 1594323:
case 4782969:
case 14348907:
case 43046721:
case 129140163:
case 387420489:
case 1162261467:return true;
default: return false;
}
}
342.power of Four
Problem Description
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Follow up:
Could you solve it without loops/recursion?
Solutioin Method
bool isPowerOfFour(int num)
{
return (num == 0x00000001) ||
(num == 0x00000004) ||
(num == 0x00000010) ||
(num == 0x00000040) ||
(num == 0x00000100) ||
(num == 0x00000400) ||
(num == 0x00001000) ||
(num == 0x00004000) ||
(num == 0x00010000) ||
(num == 0x00040000) ||
(num == 0x00100000) ||
(num == 0x00400000) ||
(num == 0x01000000) ||
(num == 0x04000000) ||
(num == 0x10000000) ||
(num == 0x40000000) ;
}