0

i have a string of numbers, and i want to multiply these numbers

string myS = "731671765313";
int product = 1;
    for(int i = 0; i<myS.length(); i++)
        product *= myS[i];

How to convert the string element to int because the result is totally wrong. I tried casting it to int but in vain.

Fadwa
  • 1,717
  • 5
  • 26
  • 43

1 Answers1

7

Use std::accumulate (because you're accumulating a product of elements, so it makes the intent clear) and recall that '0' is not 0, but that the digit characters are contiguous. For example, in ASCII, '0' is 48, '1' is 49, etc. Therefore, subtracting '0' will convert that character (if it's a digit) to the appropriate numerical value.

int product = std::accumulate(std::begin(s), std::end(s), 1, 
    [](int total, char c) {return total * (c - '0');}
);

If you can't use C++11, it's easily replaced:

int multiplyCharacterDigit(int total, char c) {
    return total * (c - '0');
}

...

int product = std::accumulate(s.begin(), s.end(), 1, multiplyCharacterDigit);

If neither of those are an option, what you had is almost there:

int product = 1;
    for(int i = 0; i<myS.length(); i++)
        product *= (myS[i] - '0');
chris
  • 60,560
  • 13
  • 143
  • 205
  • 2
    your solution requires a C++11-compliant implementation of the language, you should specify that. – user2485710 Feb 24 '14 at 00:57
  • @user2485710, As far as I'm aware, the C++ tag is C++11 by default, but I have made accommodations. – chris Feb 24 '14 at 00:58
  • @Misaki, Is there a specific problem with either of the others besides one requiring C++11, or is it just that the last one is best suited to you? I didn't exactly test the second one, so if there's something wrong, I'd be glad to fix it. – chris Feb 24 '14 at 01:07
  • "If you can't use C++", you forgot _11_ ; by the way, like you, I wish that C++11 was more popular, but older C++ standards are still more popular than C++11. – user2485710 Feb 24 '14 at 01:10
  • @chris i think the last one is simpler than the others, no need to make it complicated. Besides i want to multiply certain elements from the string. – Fadwa Feb 24 '14 at 01:10
  • @user2485710, Thanks for that. And I know what you mean, but it is gaining popularity, and it'll soon be a standard behind :) – chris Feb 24 '14 at 01:11
  • @Misaki, The others are more idiomatic is all. Someone reading it can instantly tell there's some accumulation going on. It's not too frequent when beginning, but handwritten loops are often discouraged. – chris Feb 24 '14 at 01:12