题解 | #坐标移动#
坐标移动
http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
需要考虑到以下情况:
- 当
word
长度小于2时,肯定不是“合法输入” - 当
dir
不是规定的四种,也不是“合法输入” - 当
step
不是数字时,也不是“合法输入” - 当遇到“;”时,更新
word
package main
import (
"fmt"
"strconv"
)
func move(s string, x int, y int) (int, int) {
if len(s) < 2 {
return x, y
}
dir := string(s[0])
if dir != "A" && dir != "S" && dir != "W" && dir != "D" {
return x, y
}
step, err := strconv.Atoi(string(s[1:]))
if err != nil {
return x, y
}
switch dir {
case "A":
x -= step
case "S":
y -= step
case "W":
y += step
case "D":
x += step
}
return x, y
}
func main() {
var s string
fmt.Scanf("%s", &s)
var x, y int
word := ""
for _, v := range s {
if string(v) == ";" {
x, y = move(word, x, y)
word = ""
continue
}
word += string(v)
}
xStr := strconv.Itoa(x)
yStr := strconv.Itoa(y)
res := xStr + "," + yStr
fmt.Println(res)
}