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来表示上一位,然后逐位比较即可
代码如下:
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; } };
相关文章推荐
- 某个数据通信系统采用CRC校验方式,并且生成多项式的二进制比特序列为11001,目的结点接收到的二进制比特序列为 110111001(含CRC校验码)。请判断传输过程中是否出现了差错?为什么?
- leetcode 231. Power of Two 2的幂次方数的判断 + 统计二进制数据1的数量
- 算法 Tricks(四)—— 判断序列中的字符/数值是否交替出现
- java:判断二进制数据中第n位是否为1
- EXCEL 公式使用小计 生成sql 语句 判断某一数据是否在另一列中出现
- 程序员面试题目总结--数组(五)【数组的后面m个数移动为前面m个数、列的前n项数据、判断整数x是否可以表示成n个连续正整数的和、数组中出现奇数次的元素、二维数组中的查找】
- [LeetCode]Palindrome Number 判断二进制和十进制是否为回文
- java:判断二进制数据中第n位是否为1
- P51.19(请输入一个正整数n,判断其中各位数字是否奇偶交替出现。)
- [LeetCode]—Valid Number 判断字符串是否为合法数据(科学计数法)
- [leetcode] Power of Two 判断一个数是否是2的平方
- js 去除数组中的空值以及数组判断是否有重复数据
- PHP判断输入数据是否合法常用的类
- 享受LINQ:判断一组文字是否在字符串中同时出现的最简单方法
- 布隆过滤器 解决从大量数据中快速判断是否存在相应内容
- 用ajax的同步请求解决登陆注册需要根据服务器返回数据判断是否能提交的问题
- MS SQL Server中数据表、视图、函数/方法、存储过程是否存在判断及创建
- asp.net(c#) 将dbf转换为xls或wps,并将数据的列名改成中文;并判断本机是否安装office2003,2007和wps2007,2010
- leetcode_234. Palindrome Linked List 判断单链表是否为回文串,快慢指针法找中间节点,反转单链表
- 判断二叉树是否相等(leetcode-100)