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

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.


翻譯:

給定一個正數,輸出它的補數。補數的策略是翻轉其二進制表示的位。

注意:

  1. 給定的數字保證是符合32-位有符號數的範圍。
  2. 你可以假設在數字的二進制表示前面沒有前置零位。

例子1:

輸入: 5
輸出: 2
解釋: 5的二進制表示是101(沒有前置零位),並且它的補數爲010.所以你需要輸出2。

例子2:

輸入: 1
輸出: 0
解釋: 1的二進制表示爲1(沒有前置零位),並且它的補數爲0,所以你需要輸出0。


思路:

主要需要考慮的是沒有前置零的問題,因此,我們先得到0的補數mask,然後通過和給定的數字num比較,將除了前置零位的mask的其他位都置爲0,最後用num的補數和mask進行異或。


C++代碼(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
using namespace std;

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

int main()
{
	Solution s;
	int num = 5;
	int result;
	result = s.findComplement(num);
	cout << result;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章