476. Number Complement

来源:互联网 发布:减速机 知乎 编辑:程序博客网 时间:2024/06/05 08:05

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.

比较简单,但是有个细节要注意,就是字符串的字符不能直接赋值,可以通过replace等函数替换。这里采用位运算来交换0,1

/** * @param {number} num * @return {number} */var findComplement = function(num) {    var s=num.toString(2);    var a='';    for(var n=0;n<s.length;n++){        a+=s[n]^'1';    }    return parseInt(a,2);};
0 0
原创粉丝点击