LeetCode—693. Binary Number with Alternating Bits


solution 1: 低效,每次判断最后一位bit的值,然后和上一次最后一位的bit值对比

//url:https://leetcode.com/problems/binary-number-with-alternating-bits/description/

class Solution {
public:
    bool hasAlternatingBits(int n) {
        int v=n&1;//最右边一位的bit值
        while(n>0){
            n>>=1;
            int tmp=n&1;
            //cout<<"n="<

solution 2:高效,符合条件的数,其必有以下特点
1: 该数和该数右移一位的值的与运算,其结果必然为0
2:该数和该数右移一位的值的异或运算,其结果的每一个bit位必然都为1

class Solution {
public:
    bool hasAlternatingBits(int n) {
       int v=n&(n>>1);
       if(v>0){
           return false;
       }
       v=n^(n>>1);
       while(v>0){
           if(1!=(v&1)){
               return false;
           }
           v>>=1;
       }
        return true;
    }
};

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注