您的位置:首页 > 其它

leetcode 693. Binary Number with Alternating Bits 二进制的数据是否交替出现+暴力判断

2017-12-23 17:19 375 查看
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: 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.

本题题意就是检查0和1是否是交替出现的,使用一个lastBit来表示上一位,然后逐位比较即可

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>

using namespace std;

class Solution
{
public:
bool hasAlternatingBits(int n)
{
int lastBit = -1;
while (n > 0)
{
int a = n & 1;
if (a == 1)
{
if (lastBit == 1)
return false;
else
lastBit = 1;
}
else
{
if (lastBit == 0)
return false;
else
lastBit = 0;
}
n = n >> 1;;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐