1. 程式人生 > >PAT1058:A+B in Hogwarts

PAT1058:A+B in Hogwarts

name key col bst while size title plain 處理

1058. A+B in Hogwarts (20)

時間限制 50 ms 內存限制 65536 kB 代碼長度限制 16000 B 判題程序 Standard 作者 CHEN, Yue

If you are a fan of Harry Potter, you would know the world of magic has its own currency system -- as Hagrid explained it to Harry, "Seventeen silver Sickles to a Galleon and twenty-nine Knuts to a Sickle, it‘s easy enough." Your job is to write a program to compute A+B where A and B are given in the standard form of "Galleon.Sickle.Knut" (Galleon is an integer in [0, 107

], Sickle is an integer in [0, 17), and Knut is an integer in [0, 29)).

Input Specification:

Each input file contains one test case which occupies a line with A and B in the standard form, separated by one space.

Output Specification:

For each test case you should output the sum of A and B in one line, with the same format as the input.

Sample Input:
3.2.1 10.16.27
Sample Output:
14.1.28

思路
加法,註意進位就好。

註:
1.這道題看著很簡單,然而用cin輸入的是兩個字符串,還得將字符串分割處理,然後轉換成int,有點坑。
2.直接用scanf("%d.%d.%d",&x,&y,&z)讀數據就不用處理字符串 =_=!。

代碼
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
    vector<int
> A(3),B(3); string a,b; while(cin >> a >> b) { int index = 0; //handle A for(int i = 0,j = 0;i <a.size();i++) { string tmp; if(a[i] == .) { tmp = a.substr(j,i - j); j = i + 1; A[index++] = stoi(tmp); } if(index == 2) { tmp = a.substr(j,a.size() - j); A[index++] = stoi(tmp); } } //Handle B index = 0; for(int i = 0,j = 0;i <b.size();i++) { string tmp; if(b[i] == .) { tmp = b.substr(j,i - j); j = i + 1; B[index++] = stoi(tmp); } if(index == 2) { tmp = b.substr(j,b.size() - j); B[index++] = stoi(tmp); } } int add = 0,sum = 0; sum = (A[2] + B[2]); add = sum / 29; A[2] = sum % 29; sum = A[1] + B[1] + add; add = sum/17; A[1] = sum % 17; A[0] = A[0] + B[0] + add; cout << A[0] << "." <<A[1] << "." << A[2]; } }

PAT1058:A+B in Hogwarts