1037 在霍格沃茨找零钱 (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
样例解答 1(复杂):
从小到大对每种货币依次计算。
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
String[] s1 = s[0].split("[.]");
String[] s2 = s[1].split("[.]");
int[] a = new int[3];
int[] b = new int[3];
int[] c = new int[3];
for(int i=0;i<3;i++) {
a[i] = Integer.parseInt(s1[i]);
b[i] = Integer.parseInt(s2[i]);
}
if(a[0]*17*29+a[1]*29+a[2]>b[0]*17*29+b[1]*29+b[2]) {
System.out.print("-");
if(a[2]<b[2]) {
a[2]+=29;
a[1]-=1;
}
c[2]=a[2]-b[2];
if(a[1]<b[1]) {
a[1]+=17;
a[0]-=1;
}
c[1]=a[1]-b[1];
c[0]=a[0]-b[0];
}
else {
if(b[2]<a[2]) {
b[2]+=29;
b[1]-=1;
}
c[2]=b[2]-a[2];
if(b[1]<a[1]) {
b[1]+=17;
b[0]-=1;
}
c[1]=b[1]-a[1];
c[0]=b[0]-a[0];
}
System.out.print(c[0]+"."+c[1]+"."+c[2]);
}
}
样例解答 2(简便):
直接将所有货币换成最小面值进行计算,然后在换回其他面值。
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
String[] s1 = s[0].split("[.]");
String[] s2 = s[1].split("[.]");
int[] a = new int[3];
int[] b = new int[3];
for(int i=0;i<3;i++) {
a[i] = Integer.parseInt(s1[i]);
b[i] = Integer.parseInt(s2[i]);
}
int P = a[0]*17*29+a[1]*29+a[2];
int A = b[0]*17*29+b[1]*29+b[2];
int num = A-P;
int x = Math.abs(num % 29);
int y = Math.abs(num / 29 % 17);
int z = num / 29 / 17;
System.out.print(z+"."+y+"."+x);
}
}