您的位置:首页 > 其它

[华为机试练习题]9.坐标移动

2016-03-25 11:45 344 查看
题目

开发一个坐标计算工具, A表示向左移动,D表示向右移动。W表示向上移动,S表示向下移动。从(0,0)点開始移动,从输入字符串里面读取一些坐标。并将终于输入结果输出到输出文件中面。

输入:

合法坐标为A(或者D或者W或者S) + 数字(两位以内)

坐标之间以;分隔。

非法坐标点须要进行丢弃。

如AA10; A1A; %; YAD; 等。

以下是一个简单的例子 如:

A10;S20;W10;D30;X;A1A;B10A11;;A10;

处理过程:

起点(0,0)

A10 = (-10,0)

S20 = (-10,-20)

W10 = (-10,-10)

D30 = (20,-10)

x = 无效

A1A = 无效

B10A11 = 无效

一个空 不影响

A10 = (10,-10)

结果 (10, -10)

题目类别: 字符串

难度: 中级

执行时间限制: 10Sec

内存限制: 128MByte

阶段: 入职前练习

输入:

一行字符串

输出:

终于坐标,以,分隔

例子输入:

A10;S20;W10;D30;X;A1A;B10A11;;A10;

例子输出:

10,-10

代码

/*---------------------------------------
*   日期:2015-06-29
*   作者:SJF0115
*   题目:坐标移动
*   来源:华为上机
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;

void PointMove(string str,int &x,int &y){
int size = str.size();
if(size == 0){
return;
}//if
vector<string> vec;
int start = 0,end = 0;
// 把两个分号之间的内容提取出来
while(end != -1){
end = str.find(";",start);
vec.push_back(str.substr(start,end-start));
start = end+1;
}//while
// 坐标移动
int count = vec.size();
for(int i = 0;i < count;++i){
string word = vec[i];
int len = word.size();
if(len < 1 || len > 3){
continue;
}//if
if(word[0] == 'A' || word[0] == 'D' || word[0] == 'W' || word[0] == 'S'){
int num = 0;
bool flag = true;
// 计算移动的距离
for(int j = 1;j < len;++j){
if(word[j] < '0' || word[j] > '9'){
flag = false;
break;
}//if
num = num * 10 + word[j] - '0';
}//for
// 移动距离非法
if(!flag){
continue;
}//if
if(word[0] == 'A'){
x -= num;
}//if
else if(word[0] == 'D'){
x += num;
}//else
else if(word[0] == 'W'){
y += num;
}//else
else if(word[0] == 'S'){
y -= num;
}//else
}//if
}//for
}

int main(){
string str;
//freopen("C:\\Users\\Administrator\\Desktop\\c++.txt","r",stdin);
while(getline(cin,str)){
int x = 0,y = 0;
PointMove(str,x,y);
cout<<x<<","<<y<<endl;
}//while
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: