题解 | #坐标移动#

坐标移动

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)
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务