[CF从零单排#7][字符串]339A - Helpful Maths
题目来源:http://codeforces.com/problemset/problem/339/A
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
Input
The first line contains a non-empty string s — the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.
Output
Print the new sum that Xenia can count.
Examples
input
3+2+1
output
1+2+3
input
1+1+3+1+3
output
1+1+1+3+3
input
2
output
2
题目大意:
输入一个加法式子,只有1,2,3和'+'几个字符,要将加法转化成这样的格式:加法的各项必须从小到大排序。如输入2+3+1+1,需要转化成1+1+2+3。输入长度不超过100.
题目分析:
暴力求解方法:统计输入有a个1,b个2,c个3。然后按顺序输出就可以了,中间用+号连接。注意此题用string求解,容易出错。用char[]不容易出错,因为string如果没有初始化的话,长度是默认比较短,如果后面访问到超过之前的长度,就容易出错;而char[]定义时就要求设置长度了。
参考代码:
#include <bits/stdc++.h>
using namespace std;
int main(){
char s[110], p[110];
cin >> s;
int len = strlen(s);
int a, b, c, sum;
a = b = c = 0;
for(int i=0; i<len; i++){
switch(s[i]){
case '1': a ++; break;
case '2': b ++; break;
case '3': c ++; break;
}
}
sum = a+b+c;
for(int i=1; i<=a; i++)
p[i] = '1';
for(int i=a+1; i<=a+b; i++)
p[i] = '2';
for(int i=a+b+1; i<=a+b+c; i++)
p[i] = '3';
p[sum+1] = '\0';
for(int i=1; i<sum; i++)
cout << p[i] << "+";
cout << p[sum];
return 0;
}