PAT:B1037 在霍格沃茨找零钱(20 分)
如果你是哈利·波特迷,你会知道魔法世界有它自己的货币系统 —— 就如海格告诉哈利的:“十七个银西可(Sickle)兑一个加隆(Galleon),二十九个纳特(Knut)兑一个西可,很容易。”现在,给定哈利应付的价钱 P 和他实付的钱 A,你的任务是写一个程序来计算他应该被找的零钱。
输入格式:
输入在 1 行中分别给出 P 和 A,格式为 Galleon.Sickle.Knut
,其间用 1 个空格分隔。这里 Galleon
是 [0, 107] 区间内的整数,Sickle
是 [0, 17) 区间内的整数,Knut
是 [0, 29) 区间内的整数。
输出格式:
在一行中用与输入同样的格式输出哈利应该被找的零钱。如果他没带够钱,那么输出的应该是负数。
输入样例 1:
10.16.27 14.1.28
输出样例 1:
3.2.1
输入样例 2:
14.1.28 10.16.27
输出样例 2:
-3.2.1
代码:
C/C++:
#include<cstdio>
#include<algorithm>
using namespace std;
// 29K = 1S 17S = 1G
int main() {
int G, S, K, P, A, change;
scanf("%d.%d.%d", &G, &S, &K);
P = G * (29 * 17) + S * 29 + K;
scanf("%d.%d.%d", &G, &S, &K);
A = G * (29 * 17) + S * 29 + K;
change = A - P;
if(change < 0) {
printf("-");
change = -change;
}
printf("%d.%d.%d", change/(17*29), change/29%17, change%29);
return 0;
}
Java:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int G, S, K, P, A, change;
String[] str = in.next().split("[.]");
G = Integer.parseInt(str[0]);
S = Integer.parseInt(str[1]);
K = Integer.parseInt(str[2]);
P = G * 29 * 17 + S * 29 + K;
String[] str1 = in.next().split("[.]");
G = Integer.parseInt(str1[0]);
S = Integer.parseInt(str1[1]);
K = Integer.parseInt(str1[2]);
A = G * 29 * 17 + S * 29 + K;
change = A - P;
if(change < 0) {
System.out.print("-");
change = -change;
}
System.out.printf("%d.%d.%d", change / (17 * 29), change / 29 % 17, change % 29);
}
}