# JavaScript solution ~ have a better way?

• ``````var findComplement = function (num) {
const binary = (num >>> 0).toString(2);

let complement = '';
for (let i = 0; i < binary.length; i++) {
if (binary[i] === '0') complement += '1';
else complement += '0';
}

return parseInt(complement, 2);
};
``````

• var findComplement = function(num) {
return (Math.pow(2,num.toString(2).length)-num-1);
};

• @LemonGirl damn how did you come out with that mathematical solution??

• @chengsieuly Excuse me？

• @LemonGirl I was hoping you could guide me through your solution

• @chengsieuly Give a simple example:
1001 + 0110 = 1111 = (2^4) - 1.
So, you will find that num + result = 2^(num.toString(2).length) - 1.
Did I make myself clear?

• Slightly clean solution

var findComplement = function(num) {

``````let comp = "";
for(let s of num.toString(2)){
comp += 1-parseInt(s);
}
return parseInt(comp, 2);
``````

};

• Thank u for sharing！

• Find out my solution in javascript
https://discuss.leetcode.com/topic/84346/javascript-3-lines-solution
I use bit operator to achieve this

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.