题解 | #坐标移动#

坐标移动

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

package main

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

func main() {
	var input string
	fmt.Scanln(&input)

	coordinates := strings.Split(input, ";")
	x, y := 0, 0

	for _, coordinate := range coordinates {
		if len(coordinate) < 2 {
			continue
		}
		direction := coordinate[0]
		value, err := strconv.Atoi(coordinate[1:])
		if err != nil {
			continue
		}
		switch direction {
		case 'A':
			x -= value
		case 'D':
			x += value
		case 'W':
			y += value
		case 'S':
			y -= value
		}
	}
	
	fmt.Printf("%d,%d\n", x, y)
}

这个程序首先读取输入字符串,然后使用分号将其拆分为坐标数组。接下来,它遍历每个坐标并进行处理。对于每个坐标,它检查方向和值的有效性,并根据方向更新x和y坐标。最后,它打印出最终的坐标结果。

package main

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

func main() {
	var input string
	fmt.Scanln(&input)

	coordinates := strings.Split(input, ";")
	x, y := 0, 0

	for _, coordinate := range coordinates {
		if isValid(coordinate) {
			direction := coordinate[0]
			value, err := strconv.Atoi(coordinate[1:])
			if err != nil {
				continue
			}
			switch direction {
			case 'A':
				x -= value
			case 'D':
				x += value
			case 'W':
				y += value
			case 'S':
				y -= value
			}
		}
	}

	fmt.Printf("%d,%d\n", x, y)
}

func isValid(coordinate string) bool {
	if len(coordinate) < 2 {
		return false
	}
	direction := coordinate[0]
	value := coordinate[1:]

	if direction != 'A' && direction != 'D' && direction != 'W' && direction != 'S' {
		return false
	}
	_, err := strconv.Atoi(value)
	if err != nil {
		return false
	}
	return true
}

全部评论

相关推荐

迷茫的大四🐶:都收获五个了,兄弟那还说啥,不用改了,去玩吧
点赞 评论 收藏
分享
notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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