【题目】
给定一个正整数,检查他是否为交替位二进制数:换句话说,就是他的二进制数相邻的两个位数永不相等。
来源:leetcode
链接:https://leetcode-cn.com/problems/binary-number-with-alternating-bits/
【示例】
输入: 5
输出: True
解释:
5的二进制数是: 101
【示例2】
输入: 7
输出: False
解释:
7的二进制数是: 111
【示例3】
输入: 11
输出: False
解释:
11的二进制数是: 1011
【示例4】
输入: 10
输出: True
解释:
10的二进制数是: 1010
【代码】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :5.9 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
string s[2]={"0","1"};
bool hasAlternatingBits(int n) {
string str="";
int len;
while(n){
str=s[n%2]+str;
n>>=1;
}
len=str.size();
for(int i=1;i<len;i++)
if(str[i-1]==str[i])
return false;
return true;
}
};
【位运算】
class Solution {
public:
bool hasAlternatingBits(int n) {
long a=n^(n>>1);
return (a&(a+1))==0;
}
};