The answer I get is 1364, but the correct answer is 1366.
Am I getting the wrong answer because I convert double digits = pow(2,1000)
to string dig = std::to_string(digits)
, or is there something else I'm missing?
#include <iostream>
using std::endl; using std::cout;
#include <string>
using std::string;
#include <cmath>
int computeSum(string);
int main(void){
double digits = pow(2,1000);
string dig = std::to_string(digits);
cout << computeSum(dig) << endl;
return 0;
}
int computeSum(string dig){
int sum(0);
for(char n : dig)
sum+=(n-48); // or (n-'0')
return sum;
}
EDIT:
Solution:
I needed to add the if (n!='.')
condition as (n-48)
converts the .
to its ASCII value of 46, giving me a -2.
for(char n : dig){
if(n!='.')
sum+=(n-48); // or (n-'0')
}