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
思路
这题和【1037 在霍格沃茨找零钱 (20分)】很像哈,只不过乙级的那道题实现的是减法,这题实现的是加法。
计算方式还是一样的,从低位开始看起,如果某一位相加之后,它们的和大于等于它的进制数,那就说明要进位(这里要注意的是,除了进到最高位可以直接在结果的最高位+=1,其余的进位一定要在A或B对应的数位上+=1。举个例子,假如以时分秒为例,原先是58分+1分,但是呢,两个秒相加又进了一位,因此,此时的分钟数相加应该是58分+1分+1分,也要进位,如果把这个1分钟算在结果里的话,58分+1分依然不进位,最后结果累加起来就会出现60分的情况,这应该是测试点1所考察的东西)。
最后累加完了之后直接按题目要求输出就好啦。
代码
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<string>
#include<string.h>
#include<iostream>
using namespace std;
int main()
{
int Galleon_A, Sickle_A, Knut_A, Galleon_B, Sickle_B, Knut_B;
string A, B;
cin>>A>>B;
int pos1, pos2;
pos1 = A.find(".");
Galleon_A = stoi(A.substr(0, pos1));
pos2 = A.find(".", pos1+1);
Sickle_A = stoi(A.substr(pos1+1, pos2-pos1-1));
Knut_A = stoi(A.substr(pos2+1));
pos1 = B.find(".");
Galleon_B = stoi(B.substr(0, pos1));
pos2 = B.find(".", pos1+1);
Sickle_B = stoi(B.substr(pos1+1, pos2-pos1-1));
Knut_B = stoi(B.substr(pos2+1));
int Galleon_R = 0, Sickle_R = 0, Knut_R = 0;
if(Knut_A+Knut_B>=29){
Knut_R += Knut_A+Knut_B-29;
Sickle_A += 1;
//这里不能写Sickle_R += 1,否则会出现Sickle加上Knut的进位之后需要再进一位但是没进位的情况,即:Sickle_R = 17
}
else Knut_R = Knut_A+Knut_B;
if(Sickle_A+Sickle_B>=17){
Sickle_R += Sickle_A+Sickle_B-17;
Galleon_R += 1;
}
else Sickle_R += Sickle_A+Sickle_B;
Galleon_R += Galleon_A+Galleon_B;
cout<<Galleon_R<<"."<<Sickle_R<<"."<<Knut_R;
return 0;
}