PAT 1058.A+B in Hogwarts

题目

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>

//解题思路:
//实现货币的加法运算,比较简单

using namespace std;

class Currency {
public:
friend istream &operator >> (istream &is, Currency &currency);
friend ostream &operator << (ostream &os, const Currency &currency);
friend Currency operator + (const Currency &left, const Currency &right);

Currency() = default;
Currency(int g, int s, int k) : galleon{g}, sickle{s}, knut{k}
{ }

private:
int galleon;
int sickle;
int knut;
};

istream &operator >> (istream &is, Currency &currency)
{
char c;
is >> currency.galleon >> c >> currency.sickle >> c >> currency.knut;
return is;
}

ostream &operator << (ostream &os, const Currency &currency)
{ return os << currency.galleon << "." << currency.sickle << "." << currency.knut; }

Currency operator + (const Currency &left, const Currency &right)
{
int galleon, sickle, knut;

knut = left.knut + right.knut;
sickle = left.sickle + right.sickle + knut / 29;
knut %= 29;
galleon = left.galleon + right.galleon + sickle / 17;
sickle %= 17;

return {galleon, sickle, knut};
}

int main()
{
Currency a, b;

cin >> a >> b;
cout << a + b << endl;

return 0;
}
Author: sphc
Link: https://jkuvw.xyz/archives/c40b5644/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
微信打赏
支付宝打赏