Trying to convert string array to int but doesn't work in C ++
I'm trying to solve the Euler problem of project # 16: https://projecteuler.net/problem=16 . It requires me to sum each digit from the result of 2 ^ 1000.
I am iterating over a string (converted from type double
), treating the string as an array. However, when I try to convert the string character back to int
, I always get an error.
I tried with stoi
, it will prompt me "no matching function for call to 'atoi'"
. I also tried with stringstream
to convert, it still didn't work.
See my following code:
#include <iostream>
#include <complex> // pow
#include <string> // to_string C++ 11
const double NUM = pow(2, 1000);
int main(int argc, char const *argv[]) {
int sum = 0;
//printf("%.0f\n", NUM); // Remove decimal digits
auto str = std::to_string(NUM);
std::string str_trim = str.substr(0, str.length()-7);
std::cout << str_trim << std::endl; // 2^1000 in string
for (int i = 0; i <= str_trim.length(); i++) {
std::cout << str_trim[i] << std::endl;
sum = sum + str_trim[i];
std::cout << sum << std::endl;
}
return 0;
}
Any idea to resolve this issue? Thank.
For pure coincidence, this approach will work fine on most compilers for 2 ^ 1000, because the rounding done by the IEEE754 double format (the most common floating point format in C ++) will reduce the bits by counting them as zeros (and in 2^1000
those bits indeed are zeros).
To summarize the digit, you can just iterate over the characters and do
total += s[i] - '0';
using the fact that in C ++ chars
really are small integers.
source to share
If you need to convert std::string
to int
, use std::stoi
. C ++ also has several other features for other types:std::stoi, std::stol, std::stoll, std::stoul, std::stoull, std::stof, std::stod, std::stold
However, a C ++ type cannot contain 2 ^ 1000, so you cannot use standard types and standard functions for such values.
source to share
Even if you manage to extract numbers from NUM
, your answer will be wrong:
const double NUM = pow(2, 1000);
cannot be relied upon to accurately store the number.
An alternative way to solve this problem is to evaluate 2 to 1000th cardinality in binary (the result is simple: it is 1 and then 1000 zeros). Then your problem comes down to converting that base to base 10 and summing the digits; perhaps even doing this part at the same time. But you won't be able to use any of the built-in types to represent this number. This is what makes this problem interesting.
source to share