C ++中带交替位的二进制数
假设我们有一个正整数,我们必须检查它是否具有交替位-因此,两个相邻位将始终具有不同的值。
因此,如果输入类似于10,则输出将为True,因为10的二进制表示为1010。
为了解决这个问题,我们将遵循以下步骤-
p:=n与1
如果n<2,则-
返回真
n:=n/2
当n不为零时,执行-
返回假
c:=n与1
如果cXORp等于0,则-
p:=c
n:=n/2
返回真
让我们看下面的实现以更好地理解-
示例
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool hasAlternatingBits(int n) {
bool p=n&1;
bool c;
if(n<2)
return true;
n>>=1;
while(n){
c=n&1;
if(c^p==0)
return false;
p=c;
n>>=1;
}
return true;
}
};
main(){
Solution ob;
cout << (ob.hasAlternatingBits(10));
}输入值
10
输出结果
1
热门推荐
10 韩语女儿生日祝福语简短
11 分别祝福语简短情话英文
12 新年祝福语姨姨简短
13 小班老师六一祝福语简短
14 小朋友上学祝福语简短
15 初三新年祝福语简短
16 古风考试祝福语 唯美简短
17 母亲祝福语简短微信
18 年末祝福语简短小清新