PAT Advanced 1001. A+B Format (20) (C語言實現)

我的PAT系列文章更新重心已移至Github,歡迎來看PAT題解的小伙伴請到Github Pages瀏覽最新內容。此處文章目前已更新至與Github Pages同步。歡迎star我的repo

題目

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 Specification:

Each input file contains one test case. Each case contains a pair of integers
a and b where -10^6 \le a, b \le 10^6 . The numbers are separated by a
space.

Output Specification:

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

思路

2018/1/5更新0:重要參考鏈接
Stack overflow有一個帖子專門討論如何做這個事情,我自己想到的三個也都是問題里幾個高票答案的方法,大家可以學習一下。

兩個要點:

  • 兩數和為0時要輸出0;
  • 注意逗號的輸出位置,如不要在數字前面和后面有輸出

2018/1/5更新1:

又看了一遍題,總感覺之前的代碼太繁瑣,就改了一個方法,使用字符串處理。
得到a和b后,將兩者之和輸入到一個字符串中去,使用sprintf函數。
只需要從后向前,每三個數字判斷一下是否需要加逗號即可。

2018/1/5更新2:

還有一種更省事的方法,甚至C語言里都有直接的方法處理這種事情。那就是<locale.h>頭文件,這個頭文件可以處理不同地區或者語言的輸出方式,其中就有對數字的處理。具體細節可查看相關資料,代碼放在下面

#include <stdio.h>
#include <locale.h>

int main(void)
{
    setlocale(LC_NUMERIC, "");
    printf("%'d\n", 1123456789);
    return 0;
}

更新前的代碼

代碼

最新代碼@github,歡迎交流

#include <stdio.h>
#include <string.h>

int main()
{
    int a, b, pos;
    char num[11];

    scanf("%d%d", &a, &b);
    sprintf(num, "%d", a + b);

    for(pos = strlen(num) - 3; pos > 0 && num[pos - 1] != '-'; pos -= 3)
    {
        memmove(num + pos + 1, num + pos, strlen(num) - pos + 1);
        num[pos] = ',';
    }

    puts(num);
    return 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容