Files
2022-01-05 21:45:59 -08:00

67 lines
1.7 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [1009. Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/)
## 题目
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
- For example, The integer `5` is `"101"` in binary and its **complement** is `"010"` which is the integer `2`.
Given an integer `n`, return *its complement*.
**Example 1:**
```
Input: n = 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
```
**Example 2:**
```
Input: n = 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
```
**Example 3:**
```
Input: n = 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
```
**Constraints:**
- `0 <= n < 109`
## 题目大意
每个非负整数 N 都有其二进制表示。例如 5 可以被表示为二进制 "101"11 可以用二进制 "1011" 表示依此类推。注意 N = 0 任何二进制表示中都不含前导零。
二进制的反码表示是将每个 1 改为 0 且每个 0 变为 1。例如二进制数 "101" 的二进制反码为 "010"。
给你一个十进制数 N请你返回其二进制表示的反码所对应的十进制整数。
## 解题思路
- 简单题。求一个十进制数的反码,只需要让该数和全 1 的数进行异或计算即可。所以本题重点在如何构造 mask 上。
## 代码
```go
package leetcode
func bitwiseComplement(n int) int {
mask := 1
for mask < n {
mask = (mask << 1) + 1
}
return mask ^ n
}
```