博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 693. Binary Number with Alternating Bits
阅读量:7281 次
发布时间:2019-06-30

本文共 1193 字,大约阅读时间需要 3 分钟。

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

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. 解法1:
class Solution(object):    def hasAlternatingBits(self, n):        """        :type n: int        :rtype: bool        """        # check every bit is diff from last bit        last_bit = n & 1        n = n >> 1                while n:                         bit = n & 1            if last_bit + bit != 1:                return False            last_bit = bit            n = n >> 1        return True

解法2: 移位再相加后,看是否为2的n次方

class Solution(object):    def hasAlternatingBits(self, n):        """        :type n: int        :rtype: bool        """        num = n + (n >> 1) + 1        return (num & (num-1)) == 0

解法3:直接使用bin函数

def hasAlternatingBits(self, n):        s = bin(n)        return '00' not in s and '11' not in s

 

 

转载地址:http://mukjm.baihongyu.com/

你可能感兴趣的文章
Java并发/多线程教程——3多线程的开销
查看>>
ForestDB —— 快速的 Key-Value 存储引擎
查看>>
《智能数据时代:企业大数据战略与实战》一1.5 大数据环境下的处理分析工具...
查看>>
Let's Encrypt 客户端将由EFF管理
查看>>
基于Servlet的技术问答网站系统实现(附源码)
查看>>
写给 Python 初学者的设计模式入门
查看>>
使用Redis存储Nginx+Tomcat负载均衡集群的Session
查看>>
《电路分析导论(原书第12版)》一1.3 测量单位与单位制
查看>>
《VoIP技术构架(第2版·修订版)》一第1章 PSTN概览及与VoIP的比较
查看>>
《PPT高手之道:六步变身职场幻灯派》一0.1 PPT/Presentation的本质
查看>>
fqueue初步分析
查看>>
《Node.js区块链开发》——3.3 PoS:股权证明机制
查看>>
FaceBook API
查看>>
《Swift 权威指南》——第6章,第6.11节小结
查看>>
自己动手开发一个 Web 服务器(二)
查看>>
《Node.js入门经典》一2.6 本地和全局的安装
查看>>
《Java EE核心框架实战》—— 2.4 < sql >标签
查看>>
《提高转化率!网页A/B测试与多变量测试实战指南》一2.2 掌控优化测试
查看>>
Go程序设计语言2.3 变量
查看>>
程序化交易:侠之大者为国背锅
查看>>