Our Feeds

Sunday, 6 February 2022

AJITH KP

Rescursive Sum of Digits of Number Until Becomes Single Digit

Hi All,

The bellow solution was a partial solution I used in technical round of major US based MNC technical round.

The below function will calculate the sum of all digits of number recursively until it becomes single digit.

Suppose the input number is "999", 

First iteration: it will calculate 9+9+9 = 27.  

Second iteration: it will calculate 2+7 = 9

Since 9 is single digit, we will stop the iteration and answer is "9".


Solution


#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	int num;
	cin>>num;
	while(num > 9){
		int t = num;
		int sum = 0;
		int n = 10;
		while(t > 0){
			sum += (t % 10);
			t /= n;
		}
		num = sum;
	}
	cout<<num<<endl;
	return 0;
}