Skip to content

Commit

Permalink
476 finish
Browse files Browse the repository at this point in the history
  • Loading branch information
aQua authored and aQua committed Nov 22, 2017
1 parent 5fa0b43 commit 039f067
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Algorithms/0476.number-complement/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# [476. Number Complement](https://leetcode.com/problems/number-complement/)

## 题目

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

Note:

The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.

Example 1:

```text
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:

```text
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.
```

## 解题思路

见程序注释
13 changes: 13 additions & 0 deletions Algorithms/0476.number-complement/number-complement.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package Problem0476

func findComplement(num int) int {
temp := num
res := 0
for temp > 0 {
temp >>= 1
res <<= 1
res++
}

return res ^ num
}
44 changes: 44 additions & 0 deletions Algorithms/0476.number-complement/number-complement_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package Problem0476

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

// tcs is testcase slice
var tcs = []struct {
num int
ans int
}{

{
1,
0,
},

{
5,
2,
},

// 可以有多个 testcase
}

func Test_findComplement(t *testing.T) {
ast := assert.New(t)

for _, tc := range tcs {
fmt.Printf("~~%v~~\n", tc)
ast.Equal(tc.ans, findComplement(tc.num), "输入:%v", tc)
}
}

func Benchmark_findComplement(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range tcs {
findComplement(tc.num)
}
}
}

0 comments on commit 039f067

Please sign in to comment.