题目链接:https://leetcode.com/problems/bitwise-and-of-numbers-range/
题目:
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.
思路:
32位整型,只需判断每一位在m~n之间是否有0存在,若有,该位 在AND操作中一定为0,只需判断32次
算法:
[java] view
plain copy
- public int rangeBitwiseAnd(int m, int n) {
- if (m == n)
- return m;
- int res = 0, i = 0;
- while (n != 0 && m != 0) {
- // 检查m~n是否有偶数存在时间复杂度O(1)
- boolean flag = false;
- for (int j = m; j <= n; j++) {
- int tmp = j;
- if ((tmp & 1) == 0) {// 最后一位为0
- flag = true;
- break;
- }
- }
- if (flag == false) {// 最低位全是1
- res = res | (1 << i); // 将指定为置为1
- }
- i++;
- n = n >> 1;
- m = m >> 1;
- }
- return res;
- }
时间: 2024-10-13 12:39:50