1. 程式人生 > >LeetCode 476. Number Complement (數的補數)

LeetCode 476. Number Complement (數的補數)

pan 個數 -h zeros put time for turn signed

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: 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.


題目標簽:Bit Manipulation   這道題目給了我們一個int數,讓我們找到它的補數。而且這個數字是正數,那麽我們只要把除了leading zeros的數字都反轉一下就可以了。設一個32次的for loop, 利用 & 1 來判斷最後邊的bit 是不是0, 如果是0,那麽我們需要反轉它,設一個x,規律是1,2,4,8。。。2進制, 如果是0,那麽就加x,如果是1,那麽不需要加。然後利用 >> 1來移動num 向右一位。 當num == 1的時候,意味著所有1左邊的數字都是0了,這個時候已經不需要在繼續反轉下去了。 這道題目看上去挺簡單的,但是一下子還沒做出來。。。看來今天狀態不佳,適合出去玩。

Java Solution:

Runtime beats 61.45%

完成日期:06/29/2017

關鍵詞:Bit Manipulation

關鍵點:利用 & 1 判斷最右邊的bit; 利用 >> 來移動bits;判斷num == 1 來終止反轉

 1 public class Solution 
 2 {
 3     public int findComplement(int num) 
 4     {
 5         int res = 0;
 6         int x = 1;
 7         
 8         for(int i=0; i<32; i++)
 9         {
10             if((num & 1) == 0) // meaning num‘s bit is 0, need to flip this bit.
11                 res += x;
12             
13             x = x * 2; // increase the x 
14             
15             if(num == 1) // if current num is == 1, meaning all the leading numbers are zeros; stop
16                 break;
17                 
18             num = num >> 1; // shift num to right by 1 bit.
19             
20         }
21         
22         return res;
23     }
24 }

參考資料:

http://www.cnblogs.com/grandyang/p/6275742.html

LeetCode 476. Number Complement (數的補數)