問題(Easy):
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101Example 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.
大意:
給出一個(gè)正整數(shù),檢查其是否有交替的比特位:也就是說晌块,如果相鄰的兩個(gè)比特位始終有不同的值陆爽。
例1:
輸入:5
輸出:True
解釋:
5的二進(jìn)制表示是:101例2:
輸入:7
輸出:False
解釋:
5的二進(jìn)制表示是:111例3:
輸入:11
輸出:False
解釋:
5的二進(jìn)制表示是:1011例4:
輸入:10
輸出:True
解釋:
5的二進(jìn)制表示是:1010
思路:
最簡單的就是循環(huán)右移并用模2來獲得最低位的值批销,并依次進(jìn)行比較看是否不同。
代碼(C++):
class Solution {
public:
bool hasAlternatingBits(int n) {
int temp = n % 2;
while (n > 0) {
n = n >> 1;
if (n % 2 == temp) return false;
temp = n % 2;
}
return true;
}
};
他山之石:
交替的比特位其實(shí)是個(gè)很有特點(diǎn)的排列俐填,如果右移一次,得到的數(shù)可以剛好和原本的數(shù)互補(bǔ),比如101010抡医,右移得到10101:
101010
010101
相加就會得到:
11111
我們可以利用這個(gè)特點(diǎn),如果是交替的比特位妆兑,右移一位后相加可以得到一個(gè)全是1的數(shù)魂拦,再加1會的得到一個(gè)最高位為1,其余位為0的數(shù)搁嗓,與全是1的數(shù)相與將為0芯勘,但如果不是交替的比特位,就沒有這個(gè)特性腺逛,因此可以這樣判斷荷愕,速度更快。
class Solution {
public:
bool hasAlternatingBits(int n) {
return (((long)n + (n>>1) + 1) & ((long)n + (n>>1))) == 0;
}
};
合集:https://github.com/Cloudox/LeetCode-Record