Special Sum of Array
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.
CodingNinjas
author
2y
The brute force problem will lead to overflow and hence all test cases will not pass.
So, we had to give the most optimized solution
CodingNinjas
author
2y
Brute Force
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...read more
Help your peers!
Add answer anonymously...
Top Bajaj Finserv Data Scientist interview questions & answers
Popular interview questions of Data Scientist
Top HR questions asked in Bajaj Finserv Data Scientist
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app