Binary Number with Alternating Bits(693)

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值