華為2017年機試_反轉數字求和
阿新 • • 發佈:2019-02-16
題目:
反轉數字求和。輸入“123,456”,反轉後求和:321+654=975,輸出975。
分析:
輸入的是字串,主要涉及到字串到數字的轉換,反轉可用數字求餘或字串的反轉。
用到的函式:
getline(cin, str)//輸入,以enter結束
str.find(','); //返回逗號的位置
string str1(str, pos, len); //字串的構造
stoi(str1); //string to int
#include <string>
#include <iostream>
//#include <sstream>
#include <algorithm>
using namespace std;
void reverse(string& num_s)
{
int first = 0;
int last = num_s.size()-1;
while (first < last)
swap(num_s[first++], num_s[last--]);
}
int reverseadd(string a, string b)
{
reverse(a);
reverse(b);
return stoi(a) + stoi(b);
}
int main()
{
string str;
while (getline(cin, str))
{
int pos = str.find(',');
string s1(str, 0, pos);
string s2(str, pos+1);
int res = reverseadd(s1, s2);
cout << res << endl;
}
return 0;
}