欧拉8项目 - C++

Project Euler 8 - C++

本文关键字:C++ 8项目 欧拉      更新时间:2023-10-16

我正在尝试用 c++ 解决 https://projecteuler.net/problem=8,我认为我有正确的解决方案,但我得到的值非常大或很小。只是为了提供一些信息,我将巨大的数字放入文本文件中并读取文本文件,现在我正在尝试找到最大的 13 个相邻值。这是我的代码片段,但它是最重要的部分,我正在使用uint64_t并且我得到"18436407170275213312":

uint64_t maxV = 0;
int numOfLines = 0;
uint64_t count = 1;
getline(myfile, line);
int lineLen = line.size();
int index = 0;
// Iterating through the one line
while (index < lineLen - 12)
{
    string iter = line.substr(index, 13);
    // cout << iter << endl;
    for (char e : iter)
    {
        count *= static_cast<uint64_t>(e);
    }
    if (count > maxV)
    {
        maxV = count;
    }
    count = 1;
    index++;
}
myfile.close();
cout << maxV << endl;

我知道解决方案应该是什么,但我得到的是一个更大的数字,这在数学上没有意义。我不知道我遍历强并获取计数数字的方式是错误的,还是我用来存储计数和 maxV 的类型有问题?任何帮助将不胜感激!

>变量e是一个字符。

所以如果字符是'0',则 ascii 值为 48。

当您对值 '0'(十进制 48)上的 uint64 进行static_cast时,我认为您的意思是获取值 0。
但你实际上得到值 48。

试试这个:

count *= static_cast<uint64_t>(e - '0');