Add solution 1009

This commit is contained in:
halfrost
2021-12-29 21:21:21 +08:00
parent 32a5c605c6
commit 5b5bbb2ebe
3 changed files with 128 additions and 0 deletions

View File

@ -0,0 +1,9 @@
package leetcode
func bitwiseComplement(n int) int {
mask := 1
for mask < n {
mask = (mask << 1) + 1
}
return mask ^ n
}

View File

@ -0,0 +1,52 @@
package leetcode
import (
"fmt"
"testing"
)
type question1009 struct {
para1009
ans1009
}
// para 是参数
// one 代表第一个参数
type para1009 struct {
n int
}
// ans 是答案
// one 代表第一个答案
type ans1009 struct {
one int
}
func Test_Problem1009(t *testing.T) {
qs := []question1009{
{
para1009{5},
ans1009{2},
},
{
para1009{7},
ans1009{0},
},
{
para1009{10},
ans1009{5},
},
}
fmt.Printf("------------------------Leetcode Problem 1009------------------------\n")
for _, q := range qs {
_, p := q.ans1009, q.para1009
fmt.Printf("【input】:%v 【output】:%v\n", p, bitwiseComplement(p.n))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,67 @@
# [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
}
```