Description: Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-number-with-alternating-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
For example:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
solution 1
log the previous and current bit to compare them for every iteration.
The test results:
Input a interger decimal:
5
Interger 5 has alternate bits:
Input a interger decimal:
6
Interger 6 has not alternate bits:
Input a interger decimal:
12
Interger 12 has not alternate bits:
Input a interger decimal:
23
corresponding codes:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int a{5};
bool hasAlternatingBits(int n){
int pre_num{2}, cur_num{2};
do {
cur_num = n % 2;
if (pre_num == cur_num) {
return false;
} else {
pre_num = cur_num;
n /= 2;
cur_num = n % 2;
}
} while (n != 0);
return true;
}
int main()
{
beginning:
cout << "Input a interger decimal: " << endl;
cin >> a;
bool flag = hasAlternatingBits(a);
if (flag) {
cout << "Interger " << a << " has alternate bits: " << endl;
} else {
cout << "Interger " << a << " has not alternate bits: " << endl;
}
goto beginning;
return 0;
}
solution 2
use the shitf operation to get results
The test results:
Input a interger decimal:
5
Interger 5 has alternate bits:
Input a interger decimal:
6
Interger 6 has not alternate bits:
Input a interger decimal:
7
Interger 7 has not alternate bits:
Input a interger decimal:
8
Interger 8 has not alternate bits:
corresponding codes:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int a{5};
bool hasAlternatingBits(int n){
long a = n ^ ( n >> 1 );
long flag = a & (a + 1);
return (flag == 0L);
}
int main()
{
beginning:
cout << "Input a interger decimal: " << endl;
cin >> a;
bool flag = hasAlternatingBits(a);
if (flag) {
cout << "Interger " << a << " has alternate bits: " << endl;
} else {
cout << "Interger " << a << " has not alternate bits: " << endl;
}
goto beginning;
return 0;
}