1058. A+B in Hogwarts (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, 107], Sickle is an integer in [0, 17), and Knut is an integer in [0, 29)).
输入格式:
Each input file contains one test case which occupies a line with A and B in the standard form, separated by one space.
输出格式:
For each test case you should output the sum of A and B in one line, with the same format as the input.
输入样例:
3.2.1 10.16.27
输出样例:
14.1.28
题意:
计算输入的A.B的和,然后转换进制输出
思路:
version1.0
计算出A+B的和直接输出
version2.0
设置int型变量carry存放每一位相加后的仅为
c[i] = (a[i] + b[i] +carry) % mod;
carry = (a[i] + b[i] + carry) / mod;
代码:
version1.0
/**
* @tag PAT_A_1058
* @authors R11happy (xushuai100@126.com)
* @date 2016-8-20 00:13-00:27
* @version 1.0
* @Language C++
* @Ranking 280/2992
* @function null
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int Galleon = 29*17;
const int Sickle = 29;
typedef long long LL;
int main(int argc, char const *argv[])
{
LL a1, b1, c1; //如果用int类型会导致测试点3错误
LL a2, b2, c2;
LL sum;
scanf("%lld.%lld.%lld", &a1, &b1, &c1);
scanf("%lld.%lld.%lld", &a2, &b2, &c2);
sum = (a1*Galleon+b1*Sickle+c1) + (a2*Galleon+b2*Sickle+c2);
printf("%d.%d.%d\n",int(sum / Galleon), int(sum % Galleon / Sickle), int(sum % Sickle) );
return 0;
}
version2.0
/**
* @tag PAT_A_1058
* @authors R11happy (xushuai100@126.com)
* @date 2016-8-20 00:13-00:27
* @version 1.0
* @Language C++
* @Ranking 280/2992
* @function null
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
int main(int argc, char const *argv[])
{
int a[3], b[3], c[3];
scanf("%d.%d.%d", &a[0], &a[1], &a[2]);
scanf("%d.%d.%d", &b[0], &b[1], &b[2]);
int carry = 0; //进位
c[2] = (a[2] + b[2]) % 29;
carry = (a[2] + b[2]) / 29;
c[1] = (a[1] + b[1] + carry) % 17;
carry = (a[1] + b[1] + carry) / 17;
c[0] = a[0] + b[0] + carry;
printf("%d.%d.%d\n", c[0], c[1], c[2] );
return 0;
}
c[i] = (a[i] + b[i] +carry) % mod;
carry = (a[i] + b[i] + carry) / mod;
收获:
1.int 类型可以保证8位以内都没问题,9位及9位以上要换long long
2.可以考虑version2.0加个carry的形式,这样位数再高似乎也没问题。