int32bit / leetcode

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
solve.c

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.

Code

``````int slowRangeBitwiseAnd(int m, int n) {
int ans = n;
for (int i = n - 1; i >= m && ans; --i)
ans &= i;
return ans;
}
``````

Code

```int midRangeBitwiseAnd(int m, int n)
{
int base = 1;
int t = n;
while ((t >> 1)) {
base <<= 1;
t >>= 1;
}
if (m < base)
return 0;
int ans = n;
for (int i = n - 1; i >= m; --i)
ans &= i;
return ans;
}```

Code

```int rangeBitwiseAnd(int m, int n) {
if (m == n)
return m;
if (m == 0)
return 0;
int base = 1;
int t = n;
while ((t >> 1)) {
base <<= 1;
t >>= 1;
}
int ans = 0;
while (base) {
int a = base & m;
int b = base & n;
if (a != b)
return ans;
ans |= a;
base >>= 1;
}
return ans;
}```

You can’t perform that action at this time.