Every non-negative integer
N
has a binary representation. For example,5
can be represented as"101"
in binary,11
as"1011"
in binary, and so on. Note that except forN = 0
, there are no leading zeroes in any binary representation.
The complement of a binary representation is the number in binary you get when changing every
1
to a0
and0
to a1
. For example, the complement of"101"
in binary is"010"
in binary.
For a given number
N
in base-10, return the complement of it's binary representation as a base-10 integer.
Note:
0 <= N < 10^9
This question is the same as 476: https://leetcode.com/problems/number-complement/
每個非負整數
N
都有一個二進位代表數字。例如5
在二進制可以表示成"101"
,11
則可以表示成"1011"
等等。注意,除了N = 0
以外,沒有其他以零當作開頭的數字。
一個二進制數字的補數是指把全部的
1
換成0
然後0
換成1
。例如"101"
的二進制補數就會是"010"
。
給予一個十進制數字
N
,回傳它的二進制補數並換為十進制。
提示:
0 <= N < 10^9
這個問題和476是一樣的:https://leetcode.com/problems/number-complement/
1
做XOR運算後,就會變得相反。因此現在的問題變成要怎麼避免前面多餘的零也變成一。>>
去計算N
有幾個位元digits
,再將digits
個1
去和N
做XOR就是答案了。
0
是個特例,要另做判斷。LeetCode
C++