Codeup——问题 H: 部分A+B (15)

2019-03-31 17:52:04


问题 H: 部分A+B (15)

时间限制: 1 Sec  内存限制: 32 MB
提交: 801  解决: 569
[提交][状态][讨论版][命题人:外部导入]

题目描述

正整数A的“DA(为1位整数)部分”定义为由A中所有DA组成的新整数PA。例如:给定A = 3862767,DA = 6,则A的“6部分”PA是66,因为A中有2个6。

现给定A、DA、B、DB,请编写程序计算PA + PB

输入

输入在一行中依次给出A、D A、B、D B,中间以空格分隔,其中0 < A, B < 10 10

输出

在一行中输出P A + P B的值。

样例输入

3862767 6 13530293 3
3862767 1 13530293 8

样例输出

399
0

我的算法:
把数字当做字符串输入,然后遍历某一字符串s,统计每个数字出现的个数(有个技巧,就是利用数组的下标表示数字0-9) 比如:a[i]表示数字为i时出现的此时 (0<=i<=9) 也就是说该数组长度为10
有个易错点是,我是将'6'以字符串形式输入的,那么,在找'6'是否在前一个字符串中出现过时,应当变为s[0]-'0'来访问,计数数组a[i]=>a[s[0]-'0']

代码如下:(已经AC)
 1 #include <iostream>
 2 #include<cstring>
 3 #include<sstream>
 4 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 5 using namespace std;
 6 #define ll long long 
 7 int cal_num1[10];//0-9数字
 8 
 9 
10 ll Add(int num1){
11     ll n1=0;
12 
13     while(cal_num1[num1]--){
14         n1=n1*10+num1;
15     }
16 
17     return n1;
18 
19 }
20 
21 void InitC(string s){
22     memset(cal_num1,0,sizeof(cal_num1));
23     for(int i=0;i<s.length();i++){
24         cal_num1[s[i]-'0']++;
25     }
26 }
27 int main(int argc, char** argv) {
28     string s,s1,s2,s3;
29     while(cin>>s>>s1>>s2>>s3){
30         
31         InitC(s);
32         ll n1=Add(s1[0]-'0');
33 
34         InitC(s2);
35         ll n2=Add(s3[0]-'0');
36         cout<<n1+n2<<endl;
37     
38     }
39     return 0;
40 }
如果还有更简单的做法,请指教.谢啦

猜你喜欢

转载自www.cnblogs.com/industrial-fd-2019/p/10632315.html