273. Integer to English Words

7 篇文章 0 订阅
6 篇文章 0 订阅

Task:

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?


Some Questions:

Can I use the log function?

Solution:

Obviously, we can use loop to check whether the given number is equal to 4,4^2,4^3,..,4^15. 

But how to solve it without loops? In fact, we have solve the problem power of 2. It calculates whether the given number is a divisor of (1<<30).

So, this problem can we solve it by checking whether the given number is a divisor of (4^15)? Obviously, this is not enough, because 2 is also satisfies this condition. We additionally have  to ensure it is a even power of 2. How to check it?  One way is to use log function. Let x=log(num)/log(2), if x is a even number than num is power of 4.

Another way is that let x=num|0x55555555, if x==0x55555555 than num is power of 4, because 5 is 0101 in binary system, it filters the number that the most significant digit in odd position.

Code:

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num<=0)return false;
        int HAT=1<<30;
        if(HAT%num!=0)return false;
        return (num|0x55555555)==0x55555555;
    }
};

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num<=0)return false;
        int HAT=1<<30;
        if(HAT%num!=0)return false;
        double x=log(num*1.0)/log(2.0);
        int ix=x;
        return ix%2==0;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值