题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void async function () { // Write your code here let position = [0, 0]; while(line = await readline()){ let tokens = line.split(';'); for (let token of tokens) { if (token.length <= 1 || token === ' ') { continue; } if (!"ASWD".includes(token[0])) { continue; } let num = Number(token.slice(1)); if (num === NaN || num >= 100 || Math.floor(num) !== num) { continue; } if (token[0] === 'A') { position[0] -= num; } else if (token[0] === 'S') { position[1] -= num; } else if (token[0] === 'D') { position[0] += num; } else position[1] += num; } process.stdout.write(`${position[0]},${position[1]}`); } }()
这道题重点在于识别不合法情况。注意,除了例子中给出的情况外,还有数字必须是两位数这一条件。两位数表示它必须是整数而且小于100.
对于JavaScript这种弱类型语言来说,判断很方便,直接用Number类并判断是不是NaN、判断是不是符合两位数即可。对于强类型语言,需要一个字符一个字符读入。
将字符串按照分号“;”分割,每个子串都需要判断:
- 首先排除字符串长度小于等于1的情况;
- 其次排除第一个字符不是字母,或者不是大写ASDW的情况;
- 然后读取后面的字符,应该每一个都是数字,且不能超过两位。
然后就剩下了合法的坐标,依次进行处理即可。