PAT - 甲级 - 1001. A+B Format (20)(字符串处理)
2017-11-30 21:03
369 查看
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
Sample Output
给定条件:
1.两个数字a和b
要求:
1.算出a+b
2.输出的经过每三位加一个逗号
求解:
方法1.从左往右来,如果当前位置是第四个,即三的倍数(从0开始)就输出逗号
方法2.从右往左来,每三个数字加一个逗号
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
给定条件:
1.两个数字a和b
要求:
1.算出a+b
2.输出的经过每三位加一个逗号
求解:
方法1.从左往右来,如果当前位置是第四个,即三的倍数(从0开始)就输出逗号
方法2.从右往左来,每三个数字加一个逗号
#include <cstdio> #include <cstring> using namespace std; int a, b, c; char num[10]; int main() { scanf("%d%d", &a, &b); c = a + b; sprintf(num,"%d", c); int len = strlen(num); for(int i = 0; i < len; i++) { printf("%c", num[i]); if(num[i] == '-') continue; if((len-i-1) % 3 == 0 && i != len-1) { printf(","); } } printf("\n"); return 0; }
#include <cstdio> #include <vector> using namespace std; int a, b, c; vector<char> v; int main() { scanf("%d%d", &a, &b); c = a + b; int cnt = 0; if(c < 0){ c *= -1; printf("-"); } while(c > 0) { char temp = '0' + c % 10; v.push_back(temp); cnt++; if(cnt % 3 == 0) { v.push_back(','); } c /= 10; } if(v.size() == 0){ printf("0\n"); return 0; } if(v[v.size()-1] == ',') v.pop_back(); for(int i = v.size()-1; i >= 0; i--) { printf("%c", v[i]); } return 0; }
相关文章推荐
- PAT甲题题解-1001. A+B Format (20)-字符串处理,水
- PAT - 甲级 - 1077. Kuchiguse (20)(字符串处理)
- PAT甲级1001. A+B Format(20)
- PAT甲级题解-1100. Mars Numbers (20)-字符串处理
- 【PAT甲级】【C】1001. A+B Format (20)
- 【PAT甲级】1001. A+B Format (20)
- PAT甲级1001. A+B Format (20)解题报告
- PAT - 甲级 - 1100. Mars Numbers (20)(字符串处理)
- PAT 1001. A+B Format (20)(字符串转换)
- PAT甲级1001. A+B Format (20)
- PAT - 甲级 - 1035. Password (20)(字符串处理)
- PAT - 甲级 - 1108. Finding Average (20) ( 字符串处理 sscanf )
- 浙江大学PAT_甲级_1001. A+B Format (20)
- PAT甲级.1001. A+B Format (20)
- PAT甲级 1001. A+B Format (20)
- [PAT甲级]1001. A+B Format (20)(AB和的标准输出)
- PAT甲级 1001. A+B Format (20)--两种方法
- 1001. A+B Format (20)-PAT甲级刷题
- PAT(甲级)1001. A+B Format (20)
- pat甲级1001. A+B Format (20)