【问题标题】:Error while counting number of occurrences of a character in a string [closed]计算字符串中字符的出现次数时出错[关闭]
【发布时间】: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 &lt;&lt; sizeof(long);会得到什么?
  • @NathanOliver 我得到 sizeof(long) = 4
  • 1000000000000 太大,无法放入 4 字节整数。切换到使用long long,它应该可以工作
  • 您也可以执行 std::cout
  • 您不应该创建很长的字符串并计算在内。您可以通过计算原始字符串中的出现次数并应用一些算术来做到这一点。

标签: c++ string data-structures


【解决方案1】:

long n = 1000000000000; 有一个溢出,最大 4 字节 int 是 2,147,483,647

你也在 for 循环中混合类型,这将导致溢出。

您可以考虑检查编译器警告:Live

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2023-01-28
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 2017-04-18
    • 1970-01-01
    相关资源
    最近更新 更多