如何消除挑战'Sam and sub-strings'中与模数相关的错误?
How to remove the error related to modulus in the challenge 'Sam and sub-strings'?
我在 hackerrank 上做了一个名为 Sam and sub-strings 的问题,您可以通过单击相应的 link 查看它。
这是我的代码。我确信我的程序逻辑是正确的,因为它适用于较小的值(以及示例测试用例)。问题出在模数上,我无法了解如何在此程序中正确使用模数。任何人都可以帮助我(如果可能,请告诉 when/where 在程序中使用模数而不编辑我程序的其余部分)?
我提交的测试用例 0、1、2、3、12 给出了正确的结果,而其余的给出了错误的结果。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long int n;
cin >> n;
vector<long long int> v1;
while (n!=0){
v1.push_back(n%10);
n=n/10;
}
long long int x=1,s1=0,sum=0;
for (long long int i=v1.size()-1;i>=0;i--){
s1+=x*v1[i];
x++;
sum=(sum+(s1*(long long int)pow(10,i))%1000000007)%1000000007;
}
cout << sum << endl;
return 0;
}
我建议您在玩数字时将数字视为文本。
int main()
{
std::string number_as_text;
std::cin >> number_as_text;
long long sum = 0;
const std::string::size_type length = number_as_text.length();
for (unsigned int index = 0; index < length; ++index)
{
long long s1 = (number_as_text[index] - '0') * (index + 1);
sum = sum * 10 + s1;
}
return 0;
}
如果需要,您必须弄清楚在程序中放置 mod 1000000007 的位置。
此外,我建议在代码中放置错误处理,尤其是在读取数字时。函数 std::isdigit
看起来很有帮助。
我在 hackerrank 上做了一个名为 Sam and sub-strings 的问题,您可以通过单击相应的 link 查看它。
这是我的代码。我确信我的程序逻辑是正确的,因为它适用于较小的值(以及示例测试用例)。问题出在模数上,我无法了解如何在此程序中正确使用模数。任何人都可以帮助我(如果可能,请告诉 when/where 在程序中使用模数而不编辑我程序的其余部分)? 我提交的测试用例 0、1、2、3、12 给出了正确的结果,而其余的给出了错误的结果。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long int n;
cin >> n;
vector<long long int> v1;
while (n!=0){
v1.push_back(n%10);
n=n/10;
}
long long int x=1,s1=0,sum=0;
for (long long int i=v1.size()-1;i>=0;i--){
s1+=x*v1[i];
x++;
sum=(sum+(s1*(long long int)pow(10,i))%1000000007)%1000000007;
}
cout << sum << endl;
return 0;
}
我建议您在玩数字时将数字视为文本。
int main()
{
std::string number_as_text;
std::cin >> number_as_text;
long long sum = 0;
const std::string::size_type length = number_as_text.length();
for (unsigned int index = 0; index < length; ++index)
{
long long s1 = (number_as_text[index] - '0') * (index + 1);
sum = sum * 10 + s1;
}
return 0;
}
如果需要,您必须弄清楚在程序中放置 mod 1000000007 的位置。
此外,我建议在代码中放置错误处理,尤其是在读取数字时。函数 std::isdigit
看起来很有帮助。