首页 > 其他 > 详细

Leetcode - 693. Binary Number with Alternating Bits

时间:2018-10-24 19:07:52      阅读:105      评论:0      收藏:0      [点我收藏+]

题目为

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

原文:https://www.cnblogs.com/kaezah/p/9844834.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!