题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
package main import ( "fmt" "bufio" "os" "strings" ) func isValidMove(s string) bool { size := len(s) // 长度判断 if size < 2 || size > 4 { return false } // 第一个字符判断 if s[0] != 'A' && s[0] != 'D' && s[0] != 'W' && s[0] != 'S' { return false } // 移动距离判断 for i:=1; i<size; i++ { if i == 2 && s[i-1] == '0' { return false } if s[i] < '0' || s[i] > '9' { return false } } return true } func move2distace(s string) (byte, int) { var distance int for i:=1; i<len(s); i++ { distance = distance * 10 + int(s[i] - '0') } return s[0], distance } func calculatePosition(x int, y int, moves []string) (int, int) { endX, endY := x, y for _, move := range moves { if !isValidMove(move) { continue } directon, distance := move2distace(move) if directon == 'A' { endX -= distance } else if directon == 'D' { endX += distance } else if directon == 'W' { endY += distance } else { endY -= distance } } return endX, endY } func main() { var s string inputReader := bufio.NewReader(os.Stdin) data, _, _ := inputReader.ReadLine() s = string(data) endX, endY := calculatePosition(0, 0, strings.Split(s, ";")) fmt.Printf("%d,%d\n", endX, endY) }
// 本题输入为一行字符串,故采用:inputReader.ReadLine()