[Leetcode 201, medium] Bitwise AND of Numbers Range

来源:互联网 发布:win10需要优化软件吗 编辑:程序博客网 时间:2024/06/05 21:52

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.

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

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