天天看點

PAT----1001. A+B Format (20)解題過程

1001. A+B Format (20)

github連結

PAT----1001. A+B Format (20)解題過程

時間限制

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 (有兩個逗号)
  • 最後,每種情況對應一種輸出方式;然後輸出結果。
    PAT----1001. A+B Format (20)解題過程
PAT----1001. A+B Format (20)解題過程
  • 我對照着編譯運作的結果又重新檢查了一遍,發現代碼中輸出格式出錯,逗号之後的數位要用0補齊;并且,中間三位數的算法出錯!
  • 在修改完代碼之後,成功 AC!
    PAT----1001. A+B Format (20)解題過程
PAT----1001. A+B Format (20)解題過程
PAT----1001. A+B Format (20)解題過程
PAT----1001. A+B Format (20)解題過程

pdf版本