Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
console.log(getFlags(1023));
function getFlags(sum){
  var flags = [];
  
  //if we have no sum return empty array
  if(!sum){
    return flags;
  }
  
  //check if sum is odd
  if(sum % 2 !== 0){
    //remember flag
    flags.push(1);
    
    //minus this flag from sum
    sum--;
  }
  
  //get max exponent of 2 in our sum
  var k = Math.floor(Math.log2(sum));
  while(k >= 1){
    //get max flag
    var c = Math.pow(2, k);
    
    //remember it
    flags.push(c);
    
    //minus this flag from sum
    sum = sum - c;
    
    //recount max exponent of 2 in our sum
    k = Math.floor(Math.log2(sum));
  }
  
  return flags;
}
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers