693. Binary Number with Alternating Bits

来源:互联网 发布:2015中国贸易顺差数据 编辑:程序博客网 时间:2024/06/06 03:02

题目:给定一个正整数,判断该整数的二进制形式相邻的两位是否是不同的。例子如下:

Example 1:

Input: 5Output: TrueExplanation:The binary representation of 5 is: 101

Example 2:

Input: 7Output: FalseExplanation:The binary representation of 7 is: 111.

Example 3:

Input: 11Output: FalseExplanation:The binary representation of 11 is: 1011.

Example 4:

Input: 10Output: TrueExplanation:The binary representation of 10 is: 1010.

最直接的解题思路是,求得整数的二进制形式的每一位,遍历去判断。代码如下:

class Solution {public:    bool hasAlternatingBits(int n) {        while (n) {            int temp1 = n % 2;            int temp2 = n / 2 % 2;            if (temp1 == temp2)                return false;            n /= 2;        }        return true;    }};


原创粉丝点击