题目描述

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

分析

  1. 5: 0000 0101
  2. 6: 0000 0110
  3. 7: 0000 0111
  4. ====================
  5. 共同前缀
  6. 0000 0100
  7. ********************
  8. 9: 0000 1001
  9. 10:0000 1010
  10. 11:0000 1011
  11. ===================
  12. 共同前缀
  13. 0000 0100

其实就时查找最大共同前缀。

答案

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int shift = 0;
        // 找到公共前缀
        while (m < n) {
            m >>= 1;
            n >>= 1;
            ++shift;
        }
        return m << shift;
    }
};