Find the next number by adding natural numbers in order on alternating indices from last | Java 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
class GFG { public static String generateNumber ( String number ) { int temp = 0 , adding_number = 0 ; String result = " " ; int len = number . length ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { int digit = ( int ) number . charAt ( i ) - ( int ) '0' ; if ( temp % 2 == 0 ) { adding_number += 1 ; digit += adding_number ; if ( digit >= 10 ) { digit %= 9 ; if ( digit == 0 ) digit = 9 ; } } result = digit + result ; temp += 1 ; } return result ; } public static void main ( String args [ ] ) { String S = "1345" ; System . out . println ( generateNumber ( S ) ) ; } }