[Leetcode 201, Medium] Bitwise AND of Numbers Range

来源:互联网 发布:新网互联域名过户费用 编辑:程序博客网 时间:2024/06/06 03:45

Problem:

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

Analysis:


Solutions:

C++:

    int rangeBitwiseAnd(int m, int n) {        if(m == n)            return m;        unsigned int m_temp = m;        unsigned int num_digits = 0;        while(m_temp != 0) {            ++num_digits;            m_temp /= 2;        }        unsigned int new_number = 1;        for(int i = 0; i < num_digits; ++i)            new_number *= 2;        if(new_number <= n)            return 0;        unsigned int result = m;        for(unsigned int index = m + 1; index <= n; ++index)            result &= index;        return int(result);    }
Java:


Python:

0 0
原创粉丝点击