carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode231:2 的幂(power-of-two) #68

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个整数 n,请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。 如果存在一个整数 x 使得 n == 2x ,则认为 n 是 2 的幂次方。

示例 1: 输入:n = 1 输出:true 解释:20 = 1

示例 2: 输入:n = 16 输出:true 解释:24 = 16

示例 3: 输入:n = 3 输出:false

示例 4: 输入:n = 4 输出:true

示例 5: 输入:n = 5 输出:false

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/power-of-two 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

carloscn commented 1 year ago

问题解析

使用Loop方法

定义一个伴随值,不断的递增,直到到了数据的边界,判断数据是否相等即可判断。


static bool is_power_of_two_by_loop(int64_t e)
{
    bool ret = 0;
    int64_t coherence = 1;

    if (e < 1)
        return true;

    while (coherence < e)
        coherence *= 2;

    return (coherence == e);
}

使用位运算判断

如果成立是2的幂次: 2^x = n 因为n 与 n-1 必然为0 比如8(1000) & 7(0111) -> 0(0000) 如果非2的幂次: 9(1001) & 8(1000) -> 9(1000)

static bool is_power_of_two_by_bit_op(int64_t e)
{
    if (e < 1)
        return true;

    return (e & (e - 1)) == 0;
}
carloscn commented 1 year ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/common/07_power-of-two_231.c

result:

image