Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active August 29, 2015 14:22
Show Gist options
  • Save cangoal/3b2d28731650ea1a2de5 to your computer and use it in GitHub Desktop.
Save cangoal/3b2d28731650ea1a2de5 to your computer and use it in GitHub Desktop.
LeetCode - Bitwise AND of Numbers Range
//
public int rangeBitwiseAnd(int m, int n) {
while(m<n) n = n & (n-1);
return n;
}
//
public int rangeBitwiseAnd(int m, int n) {
return (n > m) ? (rangeBitwiseAnd(m/2, n/2) << 1) : m;
}
//
public int rangeBitwiseAnd(int m, int n) {
int k = m ^ n;
int i = 30;
while(i>=0 && ((k >> i) & 1) == 0){
i--;
}
return n & ~((1 << (i+1)) - 1);
}
//
public int rangeBitwiseAnd(int m, int n) {
int ret = 0;
for(int i=30; i>=0; i--){
int low = 1 << i;
if(m >= low && n >= low){
ret += low;
m -= low;
n -= low;
}else if(m < low && n < low){
continue;
}else {
break;
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment