Number of times a number can be replaced by the sum of its digits until it only contains one digit | C ++ program to count number of times we need to add digits to get a single digit . ; Here the count variable store how many times we do sum of digits and temporary_sum always store the temporary sum we get at each iteration . ; In this loop we always compute the sum of digits in temporary_ sum variable and convert it into string str till its length become 1 and increase the count in each iteration . ; computing sum of its digits ; converting temporary_sum into string str again . ; increase the count ; Driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int NumberofTimes ( string str ) { int temporary_sum = 0 , count = 0 ; while ( str . length ( ) > 1 ) { temporary_sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) temporary_sum += ( str [ i ] - '0' ) ; str = to_string ( temporary_sum ) ; count ++ ; } return count ; } int main ( ) { string s = "991" ; cout << NumberofTimes ( s ) ; return 0 ; }