20201110: find lost number

This commit is contained in:
VicRen
2020-11-10 14:17:18 +08:00
parent f4a18fb4ed
commit 37ac2b7c2b
2 changed files with 101 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
package main
import (
"fmt"
"math/rand"
)
func main() {
r := rand.Intn(100)
fmt.Println("r:", r)
var src []int
for i := 0; i < 100; i++ {
if i == r {
continue
}
src = append(src, i)
}
fmt.Println("lost number:", findLostNumber(src))
fmt.Println("lost number2:", findLostNumber2(src))
}
func findLostNumber(nums []int) int {
sum := 0
for _, n := range nums {
sum += n
}
n := len(nums)
return n*(n+1)/2 - sum
}
func findLostNumber2(nums []int) int {
res := 0
for i, n := range nums {
res = res ^ i ^ n
}
res = res ^ len(nums)
return res
}

View File

@@ -0,0 +1,63 @@
package main
import (
"testing"
)
func Test_findLostNumber(t *testing.T) {
type args struct {
nums []int
}
tests := []struct {
name string
args args
want int
}{
{
"example_1",
args{[]int{3, 0, 1}},
2,
},
{
"example_2",
args{[]int{9, 6, 4, 2, 3, 5, 7, 0, 1}},
8,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := findLostNumber(tt.args.nums); got != tt.want {
t.Errorf("findLostNumber() = %v, want %v", got, tt.want)
}
})
}
}
func Test_findLostNumber2(t *testing.T) {
type args struct {
nums []int
}
tests := []struct {
name string
args args
want int
}{
{
"example_1",
args{[]int{3, 0, 1}},
2,
},
{
"example_2",
args{[]int{9, 6, 4, 2, 3, 5, 7, 0, 1}},
8,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := findLostNumber2(tt.args.nums); got != tt.want {
t.Errorf("findLostNumber2() = %v, want %v", got, tt.want)
}
})
}
}