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.
- This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/
給予一個正整數,回傳它的補數。補數策略是反轉他的二進制表示法的每個位元。
提示:
- 給予的數字的範圍是32位元的有號整數。
- 你可以假設不會有任何零作為開頭位元的數字出現。
- 這題和1009是一樣的題目:https://leetcode.com/problems/complement-of-base-10-integer/
1
做XOR運算後,就會變得相反。因此現在的問題變成要怎麼避免前面多餘的零也變成一。>>
去計算N
有幾個位元digits
,再將digits
個1
去和N
做XOR就是答案了。LeetCode
C++