SpringMVC 原始碼解析筆記
阿新 • • 發佈:2021-08-03
1001 A+B Format (20 分)
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 −106≤a
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
思路
程式碼
#include<cstdio> #include<cstring> int main(){ long long a, b;//兩個數相加之後用int也許會溢位 scanf("%lld%lld",&a,&b); long long sum = a + b; char z[10];//用來存放求和後的數,一個個放進去 int len = 0, flag = 0; long long sum1 = sum < 0 ? -sum : sum;//將負的和轉換為正的,當然也可以用絕對值函式 do{ z[len++] = '0' + sum1 % 10; if(len % 3 == 0) flag++;//用來記錄需要新增多少個標點 sum1 = sum1 / 10; }while(sum1 != 0); z[len] = '\0'; for(int i = 0; i < len / 2; i++){ int temp = z[i]; z[i] = z[len - 1 - i]; z[len - 1 - i] = temp; } if(sum < 0) printf("-");//如果和是負數,那麼我們先把符號輸出 for(int i = 0; i < len + flag;i++){ if(len - i != 0 && (len - i) % 3 == 0 && i != 0) printf(",");//因為標點是從後算起的,所以用len-i,但是注意無論是第一位數字前面還是最後一位數字後面都不應該有逗號 printf("%c",z[i]);一個個輸出 } return 0; }