题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <iostream> #include <vector> using namespace std; int X = 0; int Y = 0; int strToInt(string s, int begin, int end) { int res = 0; for (int i = begin; i <= end; i++) { res = res * 10 + s[i] - 48; } return res; } int main() { string s; cin >> s; string ord[10000]; int ord_len = 0; for (int i = 0; i < s.length(); i++) { if (s[i] != ';') { ord[ord_len] += s[i]; } else { ord_len++; } } for (int i = 0; i < ord_len; i++) { bool mark = true; for (int j = 1; j < ord[i].length(); j++) { if (ord[i][j] < 48 || ord[i][j] > 57) { mark = false; break; } } if (mark) {//switch case不知为何运行起来要慢2ms if (ord[i][0] == 'A') { X -= strToInt(ord[i], 1, ord[i].length() - 1); } if (ord[i][0] == 'D') { X += strToInt(ord[i], 1, ord[i].length() - 1); } if (ord[i][0] == 'W') { Y += strToInt(ord[i], 1, ord[i].length() - 1); } if (ord[i][0] == 'S') { Y -= strToInt(ord[i], 1, ord[i].length() - 1); } } } cout << X << ',' << Y << endl; return 0; }
这题不知为何与购物车那题会是同一个难度(难度定位高了)。但简单题刷着快乐啊哈哈哈哈哈
一、 字符串分割
定义一个字符串数组或者是二维char型数组(or二级指针),用于存放分割好的字符串。
用循环遍历的方式实现
int ord_len = 0; for (int i = 0; i < s.length(); i++) { if (s[i] != ';') { ord[ord_len] += s[i]; } else { ord_len++; } }
二、 检查输入是否合法
通过ASCLL码的区间判断分割完成的字符串,是否为合法可使用的字符串
bool mark = true; for (int j = 1; j < ord[i].length(); j++) { if (ord[i][j] < 48 || ord[i][j] > 57) { mark = false; break; } }
三、 类型转换
将一个数字字符串转换为其对应的十进制数(int 型)
int strToInt(string s, int begin, int end) { int res = 0; for (int i = begin; i <= end; i++) { res = res * 10 + s[i] - 48; } return res; }
然后就按着要求走就完成啦(草神の赞赏)
小草神的编程日记 文章被收录于专栏
学习编程两年半,希望大家多多关照指点