Reduce a given number to form a key by the given operations | 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
function key ( N ) { let num = " " + N . toString ( ) ; let ans = 0 ; let j = 0 ; for ( j = 0 ; j < num . length ; j ++ ) { if ( ( num [ j ] . charCodeAt ( ) - 48 ) % 2 == 0 ) { let add = 0 ; let i ; for ( i = j ; j < num . length ; j ++ ) { add += num [ j ] . charCodeAt ( ) - 48 ; if ( add % 2 == 1 ) break ; } if ( add == 0 ) { ans *= 10 ; } else { let digit = Math . floor ( Math . log10 ( add ) + 1 ) ; ans *= parseInt ( Math . pow ( 10 , digit ) , 10 ) ; ans += add ; } i = j ; } else { let add = 0 ; let i ; for ( i = j ; j < num . length ; j ++ ) { add += num [ j ] . charCodeAt ( ) - 48 ; if ( add % 2 == 0 ) { break ; } } if ( add == 0 ) { ans *= 10 ; } else { let digit = Math . floor ( Math . log10 ( add ) + 1 ) ; ans *= parseInt ( Math . pow ( 10 , digit ) , 10 ) ; ans += add ; } i = j ; } } if ( j + 1 >= num . length ) { return ans ; } else { return ans += num [ num . length - 1 ] . charCodeAt ( ) - 48 ; } } let N = 1667848271 ; document . write ( key ( N ) ) ;