zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 38-2

    Bitwise AND of Numbers Range

    思路: range内的数增量的特点是低位变化,高位不变直到进位。另外只要有变化,必然是1和0之间,所以AND肯定为0。所以只有在某个位左边的高位全相同的情况下才可能有AND为1的情况。
    细节:只需要比较边界的2个数即可,根据变化规律,中间的数高位都是相同的。

    这题可以扩展到XOR:如果低位是全域,那么XOR的值为全0

    class Solution(object):
        def rangeBitwiseAnd(self, m, n):
            """
            :type m: int
            :type n: int
            :rtype: int
            """
            res = 0
            for i in range(31, -1, -1):
                mb = (m >> i) & 1
                nb = (n >> i) & 1
                if mb!=nb: break
                if mb==1:
                    res+=(1<<i)
            return res
    
  • 相关阅读:
    10.31JS日记
    10.24JS日记
    10.23JS日记
    10.22JS日记
    10.19JS日记
    10.18JS日记
    Tomcat—Bad Request
    2016年上半年总结
    线程间操作无效
    压缩字符串的函数
  • 原文地址:https://www.cnblogs.com/absolute/p/5678266.html
Copyright © 2011-2022 走看看