Find the next number by adding natural numbers in order on alternating indices from last | C ++ program for the above approach ; Function to generate the resultant number using the given criteria ; Storing end result ; Find the length of numeric string ; Traverse the string ; Storing digit at ith position ; Checking that the number would be added or not ; Logic for summing the digits if the digit is greater than 10 ; Storing the result ; Returning the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string generateNumber ( string number ) { int temp = 0 , adding_number = 0 ; string result = " " ; int len = number . size ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { int digit = number [ i ] - '0' ; if ( temp % 2 == 0 ) { adding_number += 1 ; digit += adding_number ; if ( digit >= 10 ) { digit %= 9 ; if ( digit == 0 ) digit = 9 ; } } result = to_string ( digit ) + result ; temp += 1 ; } return result ; } int main ( ) { string S = "1345" ; cout << generateNumber ( S ) ; return 0 ; }