提问者:小点点

Hackerrank重复字符串,高值不在C++中打印


下面给出的代码即使在使用了long long并给出了一些不同的不同值之后,也不能用于高值(例如:51574523448,1000000000000等),但是可以正确地用于低值。

谁能解释一下问题是什么,怎么解决。 (抱歉英语不好)。

int repeatedString(string s, long n) {

    long count = 0;
    int secondCount = 0;
    long num;
    int length = s.length();
    double remainder;
    num = (long) n / (length);
    remainder = n % (length);

    for(int i=0; i < length; i++) {
        if(s[i]=='a') {
            count++;
            if(i < remainder)
             secondCount++;
        }
    }
    count = count*num + secondCount;

    return count;
}

共1个答案

匿名用户

请尝试在您的平台上运行此程序:

#include <iostream>
#include <limits>

int main()
{
    std::cout << std::numeric_limits<long>::max() << '\n';
}

它打印的数字是long可以存储的最大值。 我得到2147483647,比51574523448少得多。 您可能需要使用较大的数据类型,例如long long

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(hackerrank|重复|字符串|高|值|不在|c++|中|打印)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?