0

This code Find the sum of all digits that occur in a string.

Example

sumUpNumbers("2 apples, 12 oranges") = 5 //2+1+2

Can anyone explain the need for use int('0') in this code!?

int sumUpDigits(std::string inputString) {

  int answer = 0;

  for (int i = 0; i < inputString.size(); i++) {  
    if ('1' <= inputString[i] && inputString[i] <= '9') {
      answer += int(inputString[i]) - int('0');
    }
  }

  return answer;
}
Amr Ragaey
  • 1,043
  • 1
  • 10
  • 16
  • same as `(int)'0'` but with C++ syntax – user3528438 Apr 22 '15 at 23:37
  • to clarify, `int(X)` is redundant in this code. The key point is `inputstring[i] - '0'`, which is covered by the duplicate; and there are redundant casts. Whoever wrote this code didn't know the language very well. – M.M Apr 23 '15 at 00:16

1 Answers1

1

It converts char into ASCII code to make number out of string

int('9') - int('0') = 9
Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64