Skip to content

Instantly share code, notes, and snippets.

@othree
Created May 6, 2015 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save othree/367ed6f793953803c420 to your computer and use it in GitHub Desktop.
Save othree/367ed6f793953803c420 to your computer and use it in GitHub Desktop.
var rangeBitwiseAnd = function(m, n) {
if (m === 0) { return 0; }
if (m === n) { return m; }
var min = m;
var l2m = Math.floor(Math.log2(m)) + 1;
var l2n = Math.floor(Math.log2(n)) + 1;
if (l2m !== l2n) { return 0; }
var mm = 0;
while(m) {
mm = ((m & 1) == (n & 1)) ? mm + 1 : 0 ;
m = m >> 1
n = n >> 1
}
var d = l2m - mm;
var r = (min >> d) << d;
return r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment