pat 1001. A+B Format (20)
2015-07-17 06:42
411 查看
1001. A+B Format (20)
时间限制400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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
解:简单的运算,当时考虑的是从左往右每三个一组,有几个测试样例一直不过,正确的做法是从右往左每三个一组,举个例子,如2222,按标准格式输出应该是2,222,而不是222,2。其他的倒是没什么该注意的,数组保存每位的值,输出控制下即可。
贴上代码:
#include<iostream> #include<cmath> #include<cstdlib> #include<cstring> #include<cstdio> using namespace std; int main() { int a,b; while(scanf("%d%d",&a,&b)==2) { int c=a+b; int flag=0; if(c<0) flag=1; if(abs(c)/1000) { int a[10],cnt=0; string s; memset(a,0,sizeof(a)); c=abs(c); do { a[cnt++]=c%10; c=c/10; }while(c); if(flag==1) cout<<"-"; int count=0; for(int i=cnt-1;i>=0;i--) { if((i+1)%3==0&&i!=cnt-1) cout<<','; count++; cout<<a[i]; } cout<<endl; } else { printf("%d\n",c); } } return 0; }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【005-Longest Palindromic Substring(最长回文子串)】
- 【LeetCode-面试算法经典-Java实现】【004-Median of Two Sorted Arrays(两个排序数组的中位数)】
- 算法分析与设计实验四 密码算法
- 【LeetCode-面试算法经典-Java实现】【003-Longest Substring Without Repeating Characters(最长非重复子字符串)】
- 深入浅出数据分析(一)——MySQL+EXCEL+R统计问卷调查
- First Bad Version
- tar: Exiting with failure status due to previous errors
- [CareerCup] 1.7 Set Matrix Zeroes 矩阵赋零
- eclipse maven plugin 插件 安装 和 配置
- maven安装步骤
- 237 - Delete Node in a Linked List
- 中关村的那些黑暗的事——北漂18年(17)
- 203 - Remove Linked List Elements
- Implementing Stack Using Queue
- [CareerCup] 1.6 Rotate Image 翻转图像
- 关于C++中String类型的使用
- 黑马程序员-IOS学习笔记 Foundation框架下 NSArray的方法 NSMutableArray的一些方法
- hdu 1020
- 黑马程序员-IOS学习笔记 Foundation框架下 NSArray的特点和常见方法
- [CareerCup] 1.5 Compress String 压缩字符串