PAT (Advanced) 1001. A+B Format (20)
2017-09-18 23:18
459 查看
原题:1001. A+B Format (20)
解题思路:
1.将数字直接转换成反向的字符串,在适当位置加入逗号即可;
2.字符串从0开始计数,逗号位置分别为 3, 7,11 , 15…… 可发现对每个逗号出现的位置 i ,有 i % 3 在 0, 1, 2 三个数间循环,以此添加逗号即可
3.0 要特殊处理;
C++代码如下:
#include<cstdio>
#include<algorithm>
using namespace std;
char num[20];
int trans(int a)
{
int i = 0;
int x = 0;
if(a == 0)
num[i++] = '0';
while(a > 0)
{
if(i % 4 == x && i != 0)
{
x++;
x = x % 3;
num[i++] = ',';
}
num[i++] = a % 10 + '0';
a = a / 10;
}
return i;
}
int main()
{
int m, n;
while(scanf("%d%d", &m, &n) != EOF)
{
int sum = m + n;
int len = trans(abs(sum));
if(sum < 0)
printf("-");
for(int i = len - 1; i >= 0; i--)
{
printf("%c", num[i]);
}
printf("\n");
}
return 0;
}
解题思路:
1.将数字直接转换成反向的字符串,在适当位置加入逗号即可;
2.字符串从0开始计数,逗号位置分别为 3, 7,11 , 15…… 可发现对每个逗号出现的位置 i ,有 i % 3 在 0, 1, 2 三个数间循环,以此添加逗号即可
3.0 要特殊处理;
C++代码如下:
#include<cstdio>
#include<algorithm>
using namespace std;
char num[20];
int trans(int a)
{
int i = 0;
int x = 0;
if(a == 0)
num[i++] = '0';
while(a > 0)
{
if(i % 4 == x && i != 0)
{
x++;
x = x % 3;
num[i++] = ',';
}
num[i++] = a % 10 + '0';
a = a / 10;
}
return i;
}
int main()
{
int m, n;
while(scanf("%d%d", &m, &n) != EOF)
{
int sum = m + n;
int len = trans(abs(sum));
if(sum < 0)
printf("-");
for(int i = len - 1; i >= 0; i--)
{
printf("%c", num[i]);
}
printf("\n");
}
return 0;
}
相关文章推荐
- PAT(Advanced Level) 1001. A+B Format (20)
- PAT (Advanced Level) 1001. A+B Format (20)
- 【PAT (Advanced Level)】1001. A+B Format (20)
- 【c++】PAT (Advanced Level) 1001. A+B Format (20)
- PAT (Advanced Level) 1001. A+B Format (20) 解题报告
- PAT (Advanced Level) 1001. A+B Format (20) 字符串每三位添加逗号,stack辅助
- PAT(Advanced level) 1001 A+B Format(20)
- PAT (Advanced Level) Practise 1001. A+B Format (20)
- PAT (Advanced Level) Practise 1001. A+B Format (20)
- PAT (Advanced Level) Practise 1001. A+B Format (20)
- 编程题目:PAT(Advanced Level) Practice 1001. A+B Format (20)
- PAT-PAT (Advanced Level) Practise 1001. A+B Format (20) 【二星级】
- PAT-PAT (Advanced Level) Practise 1001. A+B Format (20) 【二星级】
- PAT (Advanced Level) Practise 1001. A+B Format (20)
- 【PAT】【Advanced Level】1001. A+B Format (20)
- PAT Advanced 1001. A+B Format (20) (C语言实现)
- PAT(Advanced Level)1001. A+B Format (20)
- PAT (Advanced Level) Practise 1001 A+B Format (20)
- PAT(Advanced level) 1001. A+B Format
- PAT (Advanced Level) Practise 1001. A+B Format (20)