数字的二进制表示形式是否是交替位,例如。 10101010、1010 等

问题描述 投票:0回答:1

所以我必须找出数字的二进制表示形式是否是 1 和 0 交替出现。

期望时间复杂度和空间复杂度均为O(1)

我的想法是首先找到数字的1的补码(=n),(比如说compl)

那么如果 n (AND) compl == 0 那么数字的 bin 代表是 1 和 0 交替

但是它无法正常工作

这是补函数(我昨天发现的)

    int complement(int n){
        int noOfDigits = floor(log2(n))+1;
        return ((1<<noOfDigits) - 1)^n;
    }

这是实际函数的摘录

        if(n&complement(n) == 0)return true;
        else return false;
c++ binary bit-manipulation
1个回答
0
投票

找到答案了 本来就很简单

    return (n & (n>>1)) == 0;
© www.soinside.com 2019 - 2024. All rights reserved.