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.
Solution 1:
Need to tell whether each bit contains a zero? Basically, if m - n > 2^i, where i represents for i-th bit. then i-th bit must be zero in result.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int rangeBitwiseAnd(int m, int n) { | |
if(m==n) | |
return m; | |
int diff=n-m; | |
int base; | |
while(true){ | |
int tmp=(diff-1)&diff; | |
if(tmp!=0) | |
diff=(diff-1)&diff; | |
else | |
break; | |
} | |
diff=diff<<1; | |
base=diff-1; | |
int mask=~base; | |
int res=(m&n)&mask; | |
return res; | |
} |
Consider the bits from low to high. if n>m, the lowest bit will be 0, then we could transfer the problem to sub-problem.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int rangeBitwiseAnd(int m, int n) { | |
int trans = 0; | |
while(m != n) | |
{ | |
++ trans; | |
m >>= 1; | |
n >>= 1; | |
} | |
return m << trans; | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int rangeBitwiseAnd(int m, int n) { | |
int first1Pos = 0; | |
int t = m^n; | |
for(int i=0; i<32; i++) | |
first1Pos= ((t>>i)&1)==1? i:first1Pos; | |
int res = m&n; | |
int zero=0; | |
for(int i=first1Pos; i>=0; i--){ | |
if(((res>>i)&1)==0||zero==1){ | |
res = res & (~(1<<i)); | |
zero=1; | |
} | |
} | |
return res; | |
} | |
}; |
Rnd3 sol:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int rangeBitwiseAnd(int m, int n) { | |
int res = m&n; | |
int diff = log2(n-m); | |
int tmp = 1; | |
for(int i=0; i<=diff; i++) | |
res = res&((~tmp)<<i); | |
return res; | |
} | |
}; |
No comments:
Post a Comment