题解 | #坐标移动#

坐标移动

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

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	var s string
	fmt.Scanf("%s", &s)

	ls := strings.Split(s, ";")
	lr := []string{}
	for _, v := range ls {
		if IsValid(v) {
			lr = append(lr, v)
		}
	}
	p := Position{0, 0}

	for _, v := range lr {
		Move(v, &p)
	}

	fmt.Printf("%d,%d", p.X, p.Y)
}

type Position struct {
	X int
	Y int
}

func Move(s string, p *Position) {
	d, _ := strconv.Atoi(s[1:])
	switch s[0] {
	case 'A':
		p.X -= d
	case 'D':
		p.X += d
	case 'W':
		p.Y += d
	case 'S':
		p.Y -= d
	}
}

func IsValid(s string) bool {
	if len(s) > 3 || len(s) < 2 {
		return false
	}

	if s[0] != 'A' && s[0] != 'S' && s[0] != 'W' && s[0] != 'D' {
		return false
	}

	d, err := strconv.Atoi(s[1:])
	if err != nil {
		return false
	}

	if d > 99 || d < 0 {
		return false
	}
	return true
}

全部评论

相关推荐

03-19 10:07
已编辑
广东药科大学 golang
Yki_:你倒是进一个面啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务