题解 | 坐标移动

坐标移动

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

package main

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

type P struct {
	position struct {
		x int
		y int
	}
}

func (p *P) moveUp(n int) {
	p.position.y += n
}
func (p *P) moveDown(n int) {
	p.position.y -= n
}
func (p *P) moveLeft(n int) {
	p.position.x -= n
}
func (p *P) moveRight(n int) {
	p.position.x += n
}
func (p *P) showPosition() {
	fmt.Printf("%d,%d", p.position.x, p.position.y)
}
func validStep(s string) int {
	if strings.HasPrefix(s, "0") {
		step, _ := strconv.Atoi(s)
		if step < 10 {
			return step
		} else {
			return 0
		}
	} else {
		step, _ := strconv.Atoi(s)
		if step > 99 || step < 0 {
			return 0
		}
		return step
	}
}
func main() {
	var s string
	p := new(P)
	fmt.Scan(&s)
	commands := strings.Split(s, ";")
	re := `^([WASD])(\d+)$`
	match := regexp.MustCompile(re)
	for _, command := range commands {
		args := match.FindStringSubmatch(command)
		if len(args) < 3 {
			continue
		}
		switch args[1] {
		case "W":
			p.moveUp(validStep(args[2]))
			break
		case "A":
			p.moveLeft(validStep(args[2]))
			break
		case "S":
			p.moveDown(validStep(args[2]))
			break
		case "D":
			p.moveRight(validStep(args[2]))
			break
		default:
			continue
		}
	}
	p.showPosition()
}

全部评论

相关推荐

ZywOo_求职版:谁问你了....
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
学历算污点吗?
小何和:快毕业了,BOSS上的od闻着味就来了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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