首页 > 其他分享 >leetcode 693. Binary Number with Alternating Bits

leetcode 693. Binary Number with Alternating Bits

时间:2023-05-30 18:07:14浏览次数:40  
标签:Alternating 693 return Binary Explanation binary Output Input bit

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

Example 1:

Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:

Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.

Example 3:

Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.

Example 4:

Input: 10
Output: True
Explanation:
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

 

 

标签:Alternating,693,return,Binary,Explanation,binary,Output,Input,bit
From: https://blog.51cto.com/u_11908275/6381126

相关文章

  • leetcode 637. Average of Levels in Binary Tree
    Givenanon-emptybinarytree,returntheaveragevalueofthenodesoneachlevelintheformofanarray.Example1:Input:3/\920/\157Output:[3,14.5,11]Explanation:Theaveragevalueofnodesonlevel0is3,onlevel......
  • leetcode 669. Trim a Binary Search Tree
    GivenabinarysearchtreeandthelowestandhighestboundariesasLandR,trimthetreesothatallitselementsliesin[L,R](R>=L).Youmightneedtochangetherootofthetree,sotheresultshouldreturnthenewrootofthetrimmedbinarys......
  • leetcode 617. Merge Two Binary Trees
    Giventwobinarytreesandimaginethatwhenyouputoneofthemtocovertheother,somenodesofthetwotreesareoverlappedwhiletheothersarenot.Youneedtomergethemintoanewbinarytree.Themergeruleisthatiftwonodesoverlap,thensumn......
  • leetcode 257. Binary Tree Paths
    Givenabinarytree,returnallroot-to-leafpaths.Forexample,giventhefollowingbinarytree: 1/\23\5Allroot-to-leafpathsare:["1->2->5","1->3"]#Definitionforabinarytreenode.#classTreeNode(obje......
  • leetcode 671. Second Minimum Node In a Binary Tree
    Givenanon-emptyspecialbinarytreeconsistingofnodeswiththenon-negativevalue,whereeachnodeinthistreehasexactlytwoorzerosub-node.Ifthenodehastwosub-nodes,thenthisnode'svalueisthesmallervalueamongitstwosub-nodes.G......
  • leetcode 107. Binary Tree Level Order Traversal II
    Givenabinarytree,returnthebottom-uplevelordertraversalofitsnodes'values.(ie,fromlefttoright,levelbylevelfromleaftoroot).Forexample:Givenbinarytree[3,9,20,null,null,15,7],3/\920/\157returnits......
  • can't not find Node.js binary ''path",make sure Node.js is installed and in your
    vscode中node执行debug报错报错信息如下 思路1:检查node是否安装成功win+R输入cmd  能够正常显示版本号,则证明没有问题,接着换个思路 思路2:根据提示打开图示的'launch.json'文件,在页面补充 runtimeExecutable具体补充什么内容呢?在overflow中找到了nginx中需要补......
  • 1151 LCA in a Binary Tree
    题目:Thelowestcommonancestor(LCA)oftwonodesUandVinatreeisthedeepestnodethathasbothUandVasdescendants.Givenanytwonodesinabinarytree,youaresupposedtofindtheirLCA.InputSpecification:Eachinputfilecontainsonetest......
  • 力扣 662 https://leetcode.cn/problems/maximum-width-of-binary-tree/
    需要了解树的顺序存储如果是普通的二叉树,底层是用链表去连接的如果是满二叉树,底层用的是数组去放的,而数组放的时候会有索引对应当前父节点是索引i,下一个左右节点就是2i,2i+1利用满二叉树的索引特征所以需要对每个节点进行一个索引赋值,赋值在队列中,队列用数组表示核心代码......
  • 107. Binary Tree Level Order Traversal II刷题笔记
    问题描述自底向上层序搜索python代码#Definitionforabinarytreenode.#classTreeNode:#def__init__(self,val=0,left=None,right=None):#self.val=val#self.left=left#self.right=rightclassSolution:deflevelOrd......