Sum of digits#10801

Sum of digits (Editorial)

Since the input numbers can be very large (up to digits), read them as strings. Let be a string containing the number. For example, if s = "123", the digit at the -th position of the number will be s[i] - '0'. Sum the digits of the number at all positions.

Algorithm implementation

Read the number of test cases .

cin >> n;

Process test cases sequentially.

for (i = 0; i < n; i++)
{

Read the input number into the string .

  cin >> s;

Compute the sum of the digits of the number in the variable .

  sum = 0;
  for (j = 0; j < s.size(); j++)
    sum = sum + s[j] - '0';

Print the answer.

  cout << sum << endl;
}

Python implementation

Read the number of test cases .

tests = int(input())

Process test cases sequentially.

for _ in range(tests):

Read the number as a string. Convert the input string into a list of digits.

  lst = list(map(int,input()))

The sum of the numbers in the list is equal to the sum of the digits of the current number. Print the result.

  print(sum(lst))