Special Sum of Array

Posted: 27 Nov, 2020
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You have been given an array/list ‘arr’ of length ‘N’, which contains single digit elements at every index. Your task is to return the sum of all elements of the array. But the final sum should also be a single digit.

To keep the output single digit - you need to keep adding the digits of the output number till a single digit is left.

For example:
For the given array [5, 8, 4, 9]

The sum of the elements of the array will be
5 + 8 + 4 + 9 = 26.
Since 26 is not a single-digit number, we will again take the sum of the digits of 26. 
2 + 6 = 8.
Now 8 is a single-digit number. So we will stop here and return 8.
Input Format:
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.

The first line of each test case contains a single integer ‘N’, representing the size of the array.

The second line of each test case contains ‘N’ space-separated integers representing the elements of the given array.
Output Format:
For each test case, print a single-digit integer representing the sum of the array.

Output for each test case will be printed in a separate line.
Note
You are not required to print anything, it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 100
1 <= N <= 10^3
0 <= arr[i] <= 9

It is guaranteed that the sum of ‘N’ over all test cases doesn’t exceed 10^5.

Time Limit: 1 sec.
Approach 1

We will iterate from left to right and will calculate the sum of the elements and if the sum becomes a double-digit number we will make it a single-digit number according to the steps given in the problem statement.

 

Algorithm:

 

  1. Create a variable ‘SUM’ of type integer and initialize it with zero.
  2. Start iterating the array from left to right and add the current element to the sum.
  3. If ‘SUM’ is greater than 9, create another variable ‘TempSum’, and store the sum of digits of the variable ‘SUM’ in it.
  4. Then update ‘SUM’ as ‘TempSum’.
  5. Finally, output the ‘SUM’.
Try Problem