1. 程式人生 > >Leetcode - 693. Binary Number with Alternating Bits

Leetcode - 693. Binary Number with Alternating Bits

integer self 解題思路 基本 acc sub class num different

題目為

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

Leetcode - 693. Binary Number with Alternating Bits