華爲機試題--16.座標移動

題目描述

開發一個座標計算工具, 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)

輸入描述:
一行字符串

輸出描述:
最終座標,以,分隔

輸入例子:
A10;S20;W10;D30;X;A1A;B10A11;;A10;

輸出例子:
10,-10

知識點:

string轉int

std::string str = "123";
int n = atoi(str.c_str());

int轉string

int n = 123;
std::stringstream ss;
std::string str;
ss<<n;
ss>>str;

代碼:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>

using namespace std;

int main()
{
    vector<string> input;
    string tmp;

    while (getline(cin, tmp))
    {
        //處理輸入的字符串
        //以;分割每個內容,並存入到vector<string> input中
        auto p1 = tmp.begin();
        auto index = find(p1, tmp.end(), ';');
        while (index != tmp.end())
        {
            string i(p1, index);
            p1 = index + 1;
            input.push_back(i);
            index = find(p1, tmp.end(), ';');
        }

        //Debug  查看input中存放的內容
        //for (auto i : input)
        //  cout << i << endl;


        int x = 0, y = 0;
        //處理非法輸入
        int opt = 0;
        for (auto i : input)
        {
            //僅當子字符串的開頭爲ADWS才繼續處理
            if (i[0] == 'A' || i[0] == 'D' || i[0] == 'W' || i[0] == 'S'){
                //當子字符串長度==2,也即移動數字爲1
                if (i.size() == 2)
                {
                    //僅當移動內容爲數字時處理,其餘的跳出本次循環
                    if (isdigit(i[1]))
                    {
                        //處理string到int。注意要將string轉換成c風格字符串
                        string temp(i.begin() + 1, i.end());
                        opt = atoi(temp.c_str());
                        //cout << "2:::::" << opt;
                    }
                    else
                        continue;
                }
                //A10
                else if (i.size() == 3)
                {
                    if (isdigit(i[1]) && isdigit(i[2]))
                    {
                        string temp(i.begin() + 1, i.end());
                        opt = atoi(temp.c_str());
                        //cout << "3:::::" << opt;
                    }
                    else
                        continue;
                }
                else
                    continue;

                switch (i[0])
                {
                case 'A':x -= opt; break;
                case 'D':x += opt; break;
                case 'W':y += opt; break;
                case 'S':y -= opt; break;
                }
            }
            //Debug   查看每一步的移動結果
            //cout << x << "," << y << endl;
        }
        cout << x << "," << y << endl;
        input.clear();
    }
    return  0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章