Little Bear has received a home assignment to find the sum of all digits in a number N. Following his affinity towards single digit number, he intends to repeatedly compute the sum of all digits until the sum itself becomes a single digit number.
Can you write a program to compute the final single-digit sum?
As the number N is very big, it is given in the following run length encoded format - N is represented as a sequence of M blocks, where each block i (0 ≤ i < M) is represented by two integers - (len[i], d[i]). This implies that the digit d[i] occurs len[i] number of times.
For example, {(2,1), (1,2), (2,9)} represents the number 11299.
Example:
Input: m = 3, arr = {{2, 1}, {1, 2}, {2, 9}}
Output: 4
Approach
C++
#include <bits/stdc++.h>using namespace std;#define MOD 1000000007long long recursiveSum(long long m,vector<vector<long long>> &arr){long long ans = 0;long long x = 0;for (long long i = 0; i < m; i++){long long len = arr[i][0], d = arr[i][1];ans = len * d;while (ans){x += ans % 10;ans = ans / 10;}}ans = x;while (ans >= 10){long long res = 0;while (ans){res += ans % 10;ans = ans / 10;}ans = res;}return ans;}int main(){long long m = 3;vector<vector<long long>> arr = {{2, 1}, {1, 2}, {2, 9}};cout << recursiveSum(m, arr) << "\n";return 0;}
No comments:
Post a Comment