Tuesday, August 25, 2015

Leetcode 201. Bitwise AND of Numbers Range

https://leetcode.com/problems/bitwise-and-of-numbers-range/

Bit operation. The key is to find common part from left side.

Solution:
# T:O(1) S:O(1)
class Solution:
    # @param m, an integer
    # @param n, an integer
    # @return an integer
    def rangeBitwiseAnd(self, m, n):
        i, diff = 0, n-m
        while diff:
            diff >>= 1
            i += 1
        return n&m >> i << i
Run Time: 196 ms

No comments:

Post a Comment