Transform N to Minimum possible value | CPP program to transform N to the minimum value ; Initialising the answer ; Function to find the digitsum ; Iterate over all digits and add them ; Return the digit su , ; Function to transform N to the minimum value ; If the final value is lesser than least value ; If final value is equal to least value then check for lesser number of steps to reach this value ; The value will be obtained in less than 15 steps as proved so applying normal recursive operations ; Driver code ; Function call ; Print the answers
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_val = INT_MAX ; int min_steps = 0 ; int sumOfDigits ( int n ) { string s = to_string ( n ) ; int sum = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { sum += ( s [ i ] - '0' ) ; } return sum ; } void Transform ( int n , int d , int steps ) { if ( n < min_val ) { min_val = n ; min_steps = steps ; } else if ( n == min_val ) { min_steps = min ( min_steps , steps ) ; } if ( steps < 15 ) { Transform ( sumOfDigits ( n ) , d , steps + 1 ) ; Transform ( n + d , d , steps + 1 ) ; } } int main ( ) { int N = 9 , D = 3 ; Transform ( N , D , 0 ) ; cout << min_val << " ▁ " << min_steps ; return 0 ; }