Reduce a given number to form a key by the given operations | Java program of the above approach ; Function to find the key of the given number ; Convert the integer to String ; Iterate the num - string to get the result ; Check if digit is even or odd ; Iterate until odd sum is obtained by adding consecutive digits ; Check if sum becomes odd ; Add the result in ans ; Assign the digit index to num string ; If the number is odd ; Iterate until odd sum is obtained by adding consecutive digits ; Check if sum becomes even ; Add the result in ans ; assign the digit index to main numstring ; Check if all digits are visited or not ; Driver Code
import java . io . * ; import java . util . * ; import java . lang . * ; public class Main { static int key ( int N ) { String num = " " + N ; int ans = 0 ; int j = 0 ; for ( j = 0 ; j < num . length ( ) ; j ++ ) { if ( ( num . charAt ( j ) - 48 ) % 2 == 0 ) { int add = 0 ; int i ; for ( i = j ; j < num . length ( ) ; j ++ ) { add += num . charAt ( j ) - 48 ; if ( add % 2 == 1 ) break ; } if ( add == 0 ) { ans *= 10 ; } else { int digit = ( int ) Math . floor ( Math . log10 ( add ) + 1 ) ; ans *= ( Math . pow ( 10 , digit ) ) ; ans += add ; } i = j ; } else { int add = 0 ; int i ; for ( i = j ; j < num . length ( ) ; j ++ ) { add += num . charAt ( j ) - 48 ; if ( add % 2 == 0 ) { break ; } } if ( add == 0 ) { ans *= 10 ; } else { int digit = ( int ) Math . floor ( Math . log10 ( add ) + 1 ) ; ans *= ( Math . pow ( 10 , digit ) ) ; ans += add ; } i = j ; } } if ( j + 1 >= num . length ( ) ) { return ans ; } else { return ans += num . charAt ( num . length ( ) - 1 ) - 48 ; } } public static void main ( String [ ] args ) { int N = 1667848271 ; System . out . print ( key ( N ) ) ; } }