leetcode201数字范围按位与

leetcode201 Bitwise AND of Numbers Range

Posted by BY on July 4, 2019

前言

新的一年,好好学习。

正文

问题来源

本问题来自leetcode上的201题。

问题描述

给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。

示例 1:

输入: [5,7]
输出: 4

示例 2:

输入: [0,1]
输出: 0

分析:

func rangeBitwiseAnd(m int, n int) int {
    count := 0
    for m != n {
        m = m >> 1 
        n = n >> 1 
        count++
    }
    return m << uint(count)
}

注释为递归版本,未注释为非递归版本

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        //return (n > m)?(rangeBitwiseAnd(m >> 1, n >> 1) << 1):m;
        int count = 0;
        while(n != m) 
        {
            m >>= 1;
            n >>= 1;
            count++;
        }
        return (m<<count);
    }
};

Brian Kernighan 算法

func rangeBitwiseAnd(m int, n int) int {
    for m < n {
        n = n & (n-1)
    }
    return n
}

总结:

勤思考。

结语

不管怎么样好好加油。