PAT----1001. A+B Format (20)解题过程
1001. A+B Format (20)
github链接
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
Calculate a + b and output the sum in standard format -- that is,the digits must be separated into groups of three by commas(unless there are less than four digits).
Input
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
-
Sample Input
-1000000 9
-
Sample Output
-999,991
题目大意
输入整数 a , b(-1000000 <= a, b <= 1000000);计算a,b的和;
重点是:结果要按照“三位分级法”输出。(e.g -999,991 )
解题思路
-
第一次读题后首先想到的是数组和字符串,但是实现起来有难度(如果用c++可能会好一些,但是我还没学完!),而且就算能用C语言实现,也很繁琐。所以最后还是决定用一些最基础的算法去解决这道题。
-
这道题主要考的是 三位分级法,而且-2000000<= sum <= 2000000;所以我们可以分类讨论:(设 c 为sum的绝对值,因为结果有负数,所以要用绝对值进行分类讨论)
-
C<1000 (直接输出sum)
-
1000<= C <1000000 (有一个逗号)
-
C>=1000000 (有两个逗号)
-
最后,每种情况对应一种输出方式;然后输出结果。
-
我对照着编译运行的结果又重新检查了一遍,发现代码中输出格式出错,逗号之后的数位要用0补齐;并且,中间三位数的算法出错!
-
在修改完代码之后,成功 AC!