题目:
思路:将数字转化为二进制存入数组,依次比较即可
代码:
#include <iostream>
#include <vector>
#include <array>
#include <string>
using namespace std;
class Solution {
public:
bool hasAlternatingBits(int n) {
vector<int> res;
while(n > 0){
res.push_back(n % 2);
n = n / 2;
}
for(int i = 0; i < res.size() - 1;i++){
if(res[i] == res[i+1])
return false;
}
return true;
}
};
int main(){
Solution so;
int n = 7;
cout << so.hasAlternatingBits(n) << endl;
system("pause");
return 0;
}
本文介绍了一种通过转换整数为二进制形式并检查其位是否交替的方法。使用C++实现了一个简单的程序,该程序能判断一个整数的二进制表示中相邻位是否相同。
61

被折叠的 条评论
为什么被折叠?



