數的補數 Number Complement

問題:spa

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.(輸出每一個數的補碼,實際上根據示例是要求實現按位取反)ip

Note:it

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

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

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.

解決:二進制

①  注意對輸入的數值轉換時是32位二進制數,高位爲0,不算在計算範圍內,應該跳過,從第一個非0數據開始。數據

class Solution { // 10ms
    public int findComplement(int num) {
        int tmp = (Integer.highestOneBit(num) << 1) - 1; //00..11..1
        num = ~ num;//111...取反以後的值
        return num & tmp;//000...補碼
    }
}di

進化版:異或的性質---與0相^保留原值,與1相^按位取反,與自身相^結果爲0.ant

public class Solution { // 11ms
    public int findComplement(int num) {
        int mask = (Integer.highestOneBit(num) << 1) - 1;
        return num ^ mask;
    }
}while

② 利用異或的性質。

class Solution { // 11ms
    public int findComplement(int num) {
        int tmp = num;
        int count = 0;//記錄非0的位數
        while(tmp != 0){
            tmp /= 2;
            count ++;
        }
        return num ^ (int)(Math.pow(2,count) - 1);     } }

相關文章
相關標籤/搜索