题解 | #坐标移动#

坐标移动

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

简单易懂
import java.util.Scanner;

// int[] result = {0,0}; // 结果坐标

// 函数isLegal:
// 判断是否是合法的坐标;

// 函数isNumber:
// 判断字符是否为数字字符;

// 函数move:
// 根据输入的坐标,对结果坐标进行移动

// 过程:
// 遍历坐标字符串数组: in.nextLine().split(";") {
// 先判断是否为合法坐标,是则对结果坐标进行移动
// 否则跳过;
// }
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] result = {0, 0}; // 结果坐标
        for (String o : in.nextLine().split(";")) {
            if (isLegal(o)) {
                move(result, o);
            }
        }
        System.out.print(result[0] + "," + result[1]);
    }
    
    // 判断坐标是否合法(将空字符串视为不合法)
    private static boolean isLegal(String o) {
        int len = o.length();
        if (len >= 2 && len <= 3) {
            char i = o.charAt(0);
            if (i == 'A' || i == 'D' || i == 'W' || i == 'S') {
                if (len == 2 && isNumber(o.charAt(1))) {
                    return true;
                }
                if (len == 3
                   && isNumber(o.charAt(1))
                   && isNumber(o.charAt(2))) {
                    return true;
                }
            }
        }
        return false;
    }
    
    private static boolean isNumber(char c) {
        return c >= '0' && c <= '9';
    }
    
    // 移动结果坐标
    private static void move(int[] result, String o) {
        char direction = o.charAt(0);
        int step = Integer.parseInt(o.substring(1));
        if (direction == 'A') {
            result[0] -= step;
        } else if (direction == 'D') {
            result[0] += step;
        } else if (direction == 'W') {
            result[1] += step;
        } else { // 'S'
            result[1] -= step;
        }
    }
}

#题解##笔试刷题##华为机试题#
全部评论

相关推荐

老方子:英语等级cet写错了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务