476. Number Complement
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.
Example 1:
Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
/** * @param {number} num * @return {number} */ var findComplement = function(num) { // convert num to string in binary var s= num.toString(2); // swap 1,0 var q = s.replace(/1/g, 'a'); var p = q.replace(/0/g, 'b'); p = p.replace(/b/g, 1); p = p.replace(/a/g, 0); /* convert binary string to decimal var digit = parseInt(binary, 2); */ var digit = parseInt(p, 2); return digit; };
思路:
先轉二進制
在交換01
(利用 ab 分別取代 10 接著用 01 把 ab 取代回來)
再轉回去十進制
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Syntax
parseInt(string, radix);
留言
張貼留言