1. 程式人生 > >【LeetCode & 劍指offer刷題】發散思維題6:231. Power of Two(系列)

【LeetCode & 劍指offer刷題】發散思維題6:231. Power of Two(系列)

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

231. Power of Two

Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Example 2: Input: 16 Output: true Example 3:
Input: 218 Output: false   //判斷一個整數是否為2的冪(說明必為正數) class Solution { public :    
bool isPowerOfTwo ( int n )     {         if ( n <= 0 ) return false ; //特殊情況判斷      
//  cout << ((n-1)&n) << endl;         if ( (( n - 1 )& n ) == 0 )         {             return true ; //若為2的冪,則二進位制表示中只有一個1,減一做與運算之後就會變為0         }         else return false ;         //直接換成 return ((n-1)&n) == 0;可以使程式碼更緊湊     } };   326 .   Power of Three 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? //迴圈法 /* class Solution { public:     bool isPowerOfThree(int n)     {         if(n<1) return false;         while(n%3 == 0) n /= 3; //多次除以3                 return n == 1; //如果最後商為1,則說明為3的冪     } };*/ /*取對數法 n=3^i i=log3(n) i=logb(n)/logb(3) 看i是否為整數(除以1看是否餘數為0) ,這裡選擇10為底(沒有問題,不過不明白為什麼不存在舍入誤差),若選擇自然對數,則需考慮舍入誤差 */ #include <cmath> class Solution { public :     bool isPowerOfThree ( int n )     {         return fmod ( log10 ( n )/ log10 ( 3 ), 1 ) == 0 ; //fmod為計算除法運算 x/y 的浮點餘數     } };   java:return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;   342 .   Power of Four Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Given num = 16, return true. Given num = 5, return false. Follow up : Could you solve it without loops/recursion? Credits: Special thanks to   @yukuairoy   for adding this problem and creating all test cases. /* 先判斷是否為2的冪,再判斷是否滿足(num-1)為3的倍數(必要條件,不過不知道兩個組合起來可不可以稱為充分條件) We know from Binomial Theroem that (1+X)^n = C(n,0) + C(n,1)*X + C(n,2)*X^2 + C(n,3)*X^3 +.........+ C(n,n)*X^n Put X=3, we get 4^n = 1 + C(n,1)*3 + C(n,2)*3^2 + C(n,3)*3^3 +.........+ C(n,n)*3^n by moving 1 left side, we get 4^n - 1 = C(n,1)*3 + C(n,2)*3^2 + C(n,3)*3^3 +.........+ C(n,n)*3^n i.e (4^n - 1) = 3 * [ C(n,1) + C(n,2)*3 + C(n,3)*3^2 +.........+ C(n,n)*3^(n-1) ] This implies that (4^n - 1) is multiple of 3. */ class Solution { public :     bool isPowerOfFour ( int num )     {         if ( num <= 0 ) return false ;         return (( num - 1 )& num ) == 0 && ( num - 1 )% 3 == 0 ;     } };