476. Number Complement(補數)

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

Note:spa

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

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

    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.
  3. 思路:給定一個正整數,輸出它的補數。補數的策略是經過翻轉二進位表示。
  4. 1.求出該數的二進制位數; 
    2.經過給定數num和相同位數的二進制數(全爲1)進行異或,便可求出補數。
  5.  public int findComplement(int num) {
                
                int ans = 0;//the count of the num's bits
                int temp = num;//copy of the num
                while(temp != 0){
                    ans++;
                    temp /= 2;
                }
                return num ^ (int)(Math.pow(2,ans)-1); 
        }

    pow() 函數用來求 x 的 y 次冪(次方),其原型爲:
             double pow(double x, double y);ip

相關文章
相關標籤/搜索