title: Find efficient solution of complement number
body: <p>I have been given a positive integer and asked output its complement number.</p>
  <p>i.e.</p>
  <pre><code>Input: 5
  Output: 2
  </code></pre>
  <p><strong>Explanation:</strong></p>
  <p>The binary representation of <code>5</code> is <code>101</code> (no leading zero bits), and its complement is <code>010</code>. So I need to output <code>2</code>.</p>
  <p>The following solution works but I feel it is not the most efficient algorithm. Can anyone spot any way this could be improved? Most likely using a bitwise operator.</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>/**
   * @param {number} num
   * @return {number}
   */
  var findComplement = function(num) {
  
    var bin = Number(num).toString(2);
  
    bin = bin.split('');
    var answer = [];
  
    for (var i = 0; i &lt; bin.length; i++) {
      if (bin[i] === '0') {
        answer.push(1);
      } else {
        answer.push(0)
      }
    }
  
    return parseInt(answer.join(''), 2);
  
  };
  
  console.log(findComplement(5));</code></pre>
  </div>
  </div>
  </p>