PAT甲级 1058. A+B in Hogwarts

前言

这道题是典型的自定义进制计算,20分值题,属于第一道题难度,不应该超过20分钟。

题目原文

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,10^7], 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

解决思路

有三个位,每个位的进制不同,最低位是29进制,中间位是17进制,最高位则范围在[0, 10^7]。这里还好我之前熟悉了一下sacnf()的使用,不然按以前的脑回路,因为输入中夹杂有小数点,我会用getchar()来处理输入然后转数值类型,要是真这样估计要浪费很多时间。而这里就只需要按照scanf()的输入规则,在每个说明符间写一个小数点即可按照题目要求读入。

然后计算过程是,从低位开始加,有进位就记录,最后得到最终结果。

源代码

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
#include <iostream>
#include <cstdio>

using namespace std;

int main(void) {
// input
int AG, AS, AK, BG, BS, BK;
scanf("%d.%d.%d %d.%d.%d", &AG, &AS, &AK, &BG, &BS, &BK);

// handle
int G, S, K;
int rS = 0, rK = 0;

if(AK + BK >= 29) {
K = AK + BK - 29;
rK++;
} else {
K = AK + BK;
}
if(AS + BS + rK >= 17) {
S = AS + BS + rK - 17;
rS++;
} else {
S = AS + BS + rK;
}
G = AG + BG + rS;

// output
printf("%d.%d.%d", G, S, K);

return 0;
}

后记

这道题大概用了11分钟,庆幸于之前复习了scanf()的使用,其他的可讲之处不多。