[LeetCode] Number Complement 補數

來源:互聯網
上載者:User

標籤:位置   for   mask   als   參考資料   binary   out   output   http   

 

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:

Input: 5Output: 2Explanation: 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: 1Output: 0Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

 

這道題給了我們一個數,讓我們求補數。通過分析題目匯總的例子,我們知道需要做的就是每個位翻轉一下就行了,但是翻轉的起始位置上從最高位的1開始的,前面的0是不能被翻轉的,所以我們從高往低遍曆,如果遇到第一個1了後,我們的flag就賦值為true,然後就可以進行翻轉了,翻轉的方法就是對應位異或一個1即可,參見代碼如下:

 

解法一:

class Solution {public:    int findComplement(int num) {        bool start = false;        for (int i = 31; i >= 0; --i) {            if (num & (1 << i)) start = true;            if (start) num ^= (1 << i);        }        return num;    }};

 

由於位操作裡面的取反符號~本身就可以翻轉位,但是如果直接對num取反的話就是每一位都翻轉了,而最高位1之前的0是不能翻轉的,所以我們只要用一個mask來標記最高位1前面的所有0的位置,然後對mask取反後,與上對num取反的結果即可,參見代碼如下:

 

解法二:

class Solution {public:    int findComplement(int num) {        int mask = INT_MAX;        while (mask & num) mask <<= 1;        return ~mask & ~num;    }};

 

再來看一種迭代的寫法,一行搞定碉堡了,思路就是每次都右移一位,並根據最低位的值先進行翻轉,如果當前值小於等於1了,就不用再調用遞迴函式了,參見代碼如下:

 

解法三:

class Solution {public:    int findComplement(int num) {        return (1 - num % 2) + 2 * (num <= 1 ? 0 : findComplement(num / 2));    }};

 

參考資料:

https://discuss.leetcode.com/topic/74627/3-line-c

https://discuss.leetcode.com/topic/74968/simple-java-one-line-solution

https://discuss.leetcode.com/topic/74642/java-1-line-bit-manipulation-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)

[LeetCode] Number Complement 補數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.