

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int sum1 = 0, sum2 = 0;
int sum(int i, char j)
{
int s = j - '0';
int z = 0;
while (i--)
{
z += s;
s *= 10;
}
return z;
}
int main()
{
string a, b;
int sum3;
char A, B;
cin >> a >> A >> b >> B;
for (int i = 0; i < a.size(); i++)
{
if (a[i] == A)
{
sum1++;
}
}
for (int i = 0; i < b.size(); i++)
{
if (b[i] == B)
{
sum2++;
}
}
cout << sum(sum1, A) + sum(sum2, B) << endl;
system("pause");
}
我最初的思路是通过一个数字记录Da,Db的次数,然后通过一个函数来返回答案,
但是显然很麻烦,然后就是别人写的,将函数压缩到一个式子里。我发现确实我写的垃圾

我自己的思路是。。。算了不说了(果断放弃这种思路)
ans1 = ans1 * 10 + Da - '0';
(秒呀秒呀),只会夸奖了。用例子推理一遍就会懂了,每一次都要加上个位的数字
但好像只能这题用了
#include <cstdio>
#include <iostream>
#include <stdlib.h>
using namespace std;
int ans1, ans2;
int main(void)
{
string a, b;
char Da, Db;
cin >> a >> Da >> b >> Db;
for (int i = 0; i < a.size(); i++)
{
if (a[i] == Da)
ans1 = ans1 * 10 + Da - '0';
}
for (int i = 0; i < b.size(); i++)
{
if (b[i] == Db)
ans2 = ans2 * 10 + Db - '0';
}
cout << ans1 + ans2 << endl;
system("pause");
return 0;
}
这篇博客展示了两种不同的C++代码实现,用于计算字符串中特定字符出现的次数。第一种方法使用循环和函数,而第二种方法通过简化代码直接在主函数中完成计算。博主比较了两种方法的效率,并指出第二种方法更优。文章讨论了代码优化和简洁性的主题。
363

被折叠的 条评论
为什么被折叠?



