【两次过】【位运算】Lintcode 1285: 四的乘方

本文介绍了一种高效的方法来判断一个给定的32位有符号整数是否为4的乘方。提供了两种解决方案,一种是通过循环除以4的方式进行检查,另一种则是利用位操作实现无循环验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

给定一个整数(32位有符号整数),写一个方法判断这个数字是否为4的乘方。

样例

样例 1:

输入:num = 16
输出:True

样例 2:

输入:num = 5
输出:False

挑战

你能否不使用循环/递归解决这个问题呢?


解题思路1:

    直观思路,循环num=num/4检测num%4是否为0,直到num为1为止。注意,需考虑num为0的情况,否则会陷入死循环,码代码多考虑一些边界特殊情况,再提交!

class Solution {
public:
    /**
     * @param num: an integer
     * @return: whether the integer is a power of 4
     */
    bool isPowerOfFour(int num) 
    {
        // Write your code here
        if(num == 0)
            return false;

        while(num != 1)
        {
            if(num%4 != 0)
                return false;
            num = num/4;
        }
        return true;
    }
};

解题思路2:

    显然挑战让不用循环,我们知道num & (num - 1)可以用来判断一个数是否为2的幂,其中4的幂是2的幂的一个子集,所以对2的幂做一些限制条件,观察到4的幂都是在16进制下的1 4位,那么我们只需与数(0x55555555) <==> 1010101010101010101010101010101,如果得到的数还是其本身,则可以肯定其为4的次方数。

#include<bitset>
class Solution {
public:
    /**
     * @param num: an integer
     * @return: whether the integer is a power of 4
     */
    bool isPowerOfFour(int num) 
    {
        // Write your code here
        return num>0 && !(num&(num-1)) && (num & 0x55555555)==num;
    }
};

java代码:

public class Solution {
    /**
     * @param num: an integer
     * @return: whether the integer is a power of 4
     */
    public boolean isPowerOfFour(int num) {
        // Write your code here
        return num > 0 && (num&(num-1)) == 0 && ((num&0x55555555)==num);
        
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值