【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;
    }
};
 
 
 
 

 

posted @ 2019-01-06 17:23  wikiwen  阅读(187)  评论(0编辑  收藏  举报