【发布时间】:2019-08-15 15:04:57
【问题描述】:
如果字符串 s="abcac" 且 n=10,我们考虑的子字符串是 abcacabcac,她无限字符串的前 10 个字符。子字符串中出现了 4 次“a”。
我的代码在上述和其他一些示例中运行良好,但是当我输入字符串 s="a" 和 n = 1000000000000 时,我得到的输出为 0。我不明白为什么我一直得到 0 ;
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
long repeatedString(string s, long n)
{
long long count = 0;
string s1 = s;
//adding the string upto n times
for (long long i = 0; i < n; i++)
{
s += s1;
if (s.size() >= n)
break;
}
//looping to find number of occurances of "a"
for (long long i = 0; i < s.size(); i++)
{
if (s[i] == 'a')
count++;
}
return count;
}
int main()
{
string s = "a";
long n = 1000000000000; //getting 0 for this input
long p = repeatedString(s, n);
cout << p << endl;
return 0;
}
【问题讨论】:
-
如果你这样做
std::cout << sizeof(long);会得到什么? -
@NathanOliver 我得到 sizeof(long) = 4
-
1000000000000太大,无法放入 4 字节整数。切换到使用long long,它应该可以工作 -
您也可以执行 std::cout
-
您不应该创建很长的字符串并计算在内。您可以通过计算原始字符串中的出现次数并应用一些算术来做到这一点。
标签: c++ string data-structures