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;
}
};
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2018/08/03/leetcode-693-binary-number-with-alternating-bits/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!