题解 | 坐标移动
坐标移动
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()
}
字节跳动工作强度 1114人发布
查看6道真题和解析