题目:给定一个正整数,判断该整数的二进制形式相邻的两位是否是不同的。例子如下:
Example 1:
Input: 5 Output: True Explanation: The binary representation of 5 is: 101
Example 2:
Input: 7 Output: False Explanation: The binary representation of 7 is: 111.
Example 3:
Input: 11 Output: False Explanation: The binary representation of 11 is: 1011.
Example 4:
Input: 10 Output: True Explanation: The binary representation of 10 is: 1010.
最直接的解题思路是,求得整数的二进制形式的每一位,遍历去判断。代码如下:
class Solution {
public:
bool hasAlternatingBits(int n) {
while (n) {
int temp1 = n % 2;
int temp2 = n / 2 % 2;
if (temp1 == temp2)
return false;
n /= 2;
}
return true;
}
};