题解 | #坐标移动#

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

package main

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

func main() {
	// 输出结果
	result := []int{0, 0}

	// 读取终端内容并处理
	reader := bufio.NewReader(os.Stdin)
	input, _ := reader.ReadString('\n')
	input = strings.TrimRight(input, "\n")

	// 有效的操作符
	validMap := map[string]string{
		"A": "A",
		"S": "S",
		"D": "D",
		"W": "W",
	}

	// 单独处理每个操作符
	operateList := strings.Split(input, ";")
	for _, operation := range operateList {
		// 合法坐标为A(或者D或者W或者S) + 数字(两位以内)
		length := len(operation)
		if length <= 1 || length >= 4{
			continue
		}

        // 操作符是否有效
		val, ok := validMap[string(operation[0])]
        if !ok{
            continue
        }

        // 将字符转换为数字,转换失败则跳过
		num, err := strconv.Atoi(operation[1:])
		if err != nil {
			continue
		}

        // 根据操作类型修改位置
		switch val {
		case "A":
			result[0] -= num
		case "S":
			result[1] -= num
		case "D":
			result[0] += num
		case "W":
			result[1] += num
		}
	}

	fmt.Printf("%d,%d\n", result[0], result[1])
}

#刷题记录#
od刷题-golang 文章被收录于专栏

华为机试刷题内容记录

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务