上机编程认证02

/*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2021. All rights reserved.
* Description: 上机编程认证
* Note: 缺省代码仅供参考,可自行决定使用、修改或删除
* 只能import Go标准库
*/
package main

import (
"bufio"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
)

// 待实现函数,在此函数中填入答题代码
func getTop3Num(input string) []int {
//按规则抽取所有的数字
//规则1.紧靠数字的-号表示负数
//规则2.前面的0需要去掉
//规则3.从大到小排序取前三
nums := []int{}
boxString := ""
boxTagForNegative := -1000
boxTagForIntval := false
for key,value := range input {
if string(value) == "-" {
boxTagForNegative = key
}
if string(value) >="0" && string(value) <= "9" && boxTagForIntval == false{
boxTagForIntval = true
}
if key - boxTagForNegative == 1 {
boxTagForNegative = -1000
if boxTagForIntval {
boxString = "-"
boxString += string(value)
boxTagForIntval = false
continue
}
}

if boxTagForIntval {
boxString += string(value)
boxTagForIntval = false
boxTagForNegative = -1000
if key == len(input) - 1 {
boxInt,err := strconv.Atoi(boxString)
if err == nil{
nums = append(nums,boxInt)
boxString = ""
}
}
continue
}

if boxString != "" && !boxTagForIntval {
boxInt,err := strconv.Atoi(boxString)
if err == nil {
nums = append(nums,boxInt)
boxString = ""
}
}

}
sort.Sort(sort.Reverse(sort.IntSlice(nums)))
if len(nums) >= 3 {
return nums[0:3]
} else {
return nums
}
}

func main() {
inputReader := bufio.NewReader(os.Stdin)
lineBuf, err := inputReader.ReadString('\n')
if err != nil && err != io.EOF {
fmt.Println(err.Error())
return
}
input := strings.TrimRight(lineBuf, "\r\n")
result := getTop3Num(input)
fmt.Print("[")
for i := 0; i < len(result); i++ {
if i == 0 {
fmt.Print(strconv.Itoa(result[i]))
} else {
fmt.Print(" " + strconv.Itoa(result[i]))
}
}
fmt.Print("]")
}


a56b-6-8()_56!@$-a
提示:输入字符串四个数字 56,-6,-8,56 取最大
[56 56 -6]



--028.300003
提示:抽取 -28,300003
[300003 -28]



//test


package main

import (
"strconv"
"testing"
)

type testStruct struct {
inputStr string
want string
}

func TestSomeFunction(t *testing.T) {
tests := []testStruct{
{inputStr: "a56b-6-8()_56!@$-a",want: "5656-6"},
}
for _,tt := range tests {
result := getTop3Num(tt.inputStr)
got := ""
for i := 0; i < len(result); i++ {
got += strconv.Itoa(result[i])
}
if got != tt.want {
t.Errorf("getTop3Num(%v) = %v, want %v", tt.inputStr, got, tt.want)
}
}
}


posted @ 2022-04-09 19:46  易先讯  阅读(113)  评论(0编辑  收藏  举报