LeetCode – 476. Number Complement

題目來源:LeetCode -476. Number Complement


題目:

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

Note:

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

Example 1:

Example 2:

粗略翻譯:

給定一個數,我們必須回傳該數的一補數,例如數字5在二進位中表示為(101)

經過一補數的反轉後則是(010),因此回傳數字2

解法:

以例子來說,如果輸入的數字為5,在二進位代表(101)

如果三位數的二進位皆是1,那麼就是數字7,二進位代表(111)

將7減5則會得到2,二進位代表(010)

因此我們跑一個迴圈,讓i從1開始,並加到變數complement上

並將i向左一個位元,在持續加到complement

一直到complement比num大為止,最後將complement減num即是答案


網站:http://wp.mlab.tw/
GitHub:https://github.com/yoll522/LeetCode
程式碼:https://github.com/yoll522/LeetCode/tree/master/476.%20Number%20Complement

Leave a Reply

你的電子郵件位址並不會被公開。 必要欄位標記為 *