PAT Class B 1037 Finding Change at Hogwarts (Problem Solving Ideas + AC Code)

topic:

If you're a Harry Potter fan, you know that the wizarding world has its own currency system - as Hagrid told Harry: "Seventeen Sickles to one Galleon, It's easy to exchange twenty-nine Knuts for one Sickle." Now, given the price P that Harry pays and the amount A he actually pays , your task is to write a program to calculate the amount he should be given. small change.

Input format:

The input gives P and A respectively on 1 line in the format Galleon.Sickle.Knut, separated by 1 space. Here Galleonis an integer in the interval [0, 107], Sicklean integer in the interval [0, 17), Knutan integer in the interval [0, 29).

Output format:

Output the change that Harry should be given in the same format as input on one line. If he did not bring enough money, then the output should be negative.

Input sample 1:

10.16.27 14.1.28

Output sample 1:

3.2.1

Input sample 2:

14.1.28 10.16.27

Output sample 2:

-3.2.1

Code length limit 16 KB
time limit 400 ms
memory limit 64 MB

 

problem solving ideas

  • My idea is to define a subtraction function of my own. The implementation details in it are actually simulating our decimal subtraction. The only difference is that our function can only perform large reduction operations.
  • So how to achieve small reduction? For example 2.3.4 - 3.4.5. In fact, we only use the analogy of the decimal system. Assuming that the decimal system is 35-36, the answer is obviously -1. If we use the function we defined to calculate, then the result of the calculation is -19, the answer is obviously wrong, we need to subtract -19 from 0, and we get 1 at this time, so we need to assign the first digit to negative number.

 

AC code

#include <bits/stdc++.h>
using namespace std;

//my_minus
void my_minus(int p1, int p2, int p3, int a1, int a2, int a3
             ,int& ret_1, int& ret_2, int& ret_3)
{
    
    
    if (a3 >= p3)
    {
    
    
        ret_3 = a3 - p3;
    }
    else
    {
    
    
        ret_3 = a3 + 29 - p3;
        a2--;
    }
    
    if (a2 >= p2)
    {
    
    
        ret_2 = a2 - p2;
    }
    else
    {
    
    
		ret_2 = a2 + 17 - p2;
        a1--;
    }
    
    ret_1 = a1 - p1;
}

int main()
{
    
    
    int p1, p2, p3, a1, a2, a3, ret_1, ret_2, ret_3;
    scanf("%d.%d.%d %d.%d.%d", &p1, &p2, &p3, &a1, &a2, &a3);
    my_minus(p1, p2, p3, a1, a2, a3, ret_1, ret_2, ret_3);
    if (ret_1 < 0)
    {
    
    
        my_minus(ret_1, ret_2, ret_3, 0, 0, 0, ret_1, ret_2, ret_3);
        ret_1 *= -1;
    }
    printf("%d.%d.%d", ret_1, ret_2, ret_3);
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_70103775/article/details/130737353