Number of times a number can be replaced by the sum of its digits until it only contains one digit | PHP 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 Code
< ? php function NumberofTimes ( $ str ) { $ temporary_sum = 0 ; $ count = 0 ; while ( strlen ( $ str ) > 1 ) { $ temporary_sum = 0 ; for ( $ i = 0 ; $ i < strlen ( $ str ) ; $ i ++ ) $ temporary_sum += ( $ str [ $ i ] - '0' ) ; $ str = ( string ) ( $ temporary_sum ) ; $ count ++ ; } return $ count ; } $ s = "991" ; echo NumberofTimes ( $ s ) ; ? >