Leetcode - 693. Binary Number with Alternating Bits

题目为

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

解题思路:

题设要求判断形如101010的数字,那么如何在复杂度最小的情况下给出算法呢

首先看一下用python解决本题有哪些基本工具。

说到二进制,首先想到的是位运算符号,python的位运算符号有& ^ ~ | >> <<这六种。

先看移位,易发现如果将101010右移一位,则有10101,两者相加为111111;当111111进1则与其本身的与运算就得到0

尝试编写解题代码如下:

class Solution:
    def hasAlternatingBits(self, n):
        return ((n + (n >> 1) ) & (n + (n >> 1)+1)) == 0

Submission Result: Accepted 

 

posted @ 2018-10-24 17:37  kaezah  阅读(102)  评论(0)    收藏  举报