Reduce a given number to form a key by the given operations | Python3 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 ;
import math NEW_LINE def key ( N ) : NEW_LINE INDENT num = " " + str ( N ) NEW_LINE ans = 0 NEW_LINE j = 0 NEW_LINE while j < len ( num ) : NEW_LINE INDENT if ( ( ord ( num [ j ] ) - 48 ) % 2 == 0 ) : NEW_LINE INDENT add = 0 NEW_LINE i = j NEW_LINE while j < len ( num ) : NEW_LINE INDENT add += ord ( num [ j ] ) - 48 NEW_LINE if ( add % 2 == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( add == 0 ) : NEW_LINE INDENT ans *= 10 NEW_LINE DEDENT else : NEW_LINE INDENT digit = int ( math . floor ( math . log10 ( add ) + 1 ) ) NEW_LINE ans *= ( pow ( 10 , digit ) ) NEW_LINE ans += add NEW_LINE DEDENT i = j NEW_LINE DEDENT else : NEW_LINE INDENT add = 0 NEW_LINE i = j NEW_LINE while j < len ( num ) : NEW_LINE INDENT add += ord ( num [ j ] ) - 48 NEW_LINE if ( add % 2 == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( add == 0 ) : NEW_LINE INDENT ans *= 10 NEW_LINE DEDENT else : NEW_LINE INDENT digit = int ( math . floor ( math . log10 ( add ) + 1 ) ) NEW_LINE ans *= ( pow ( 10 , digit ) ) NEW_LINE ans += add NEW_LINE DEDENT i = j NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j + 1 ) >= len ( num ) : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT ans += ord ( num [ len ( num ) - 1 ] ) - 48 NEW_LINE return ans NEW_LINE DEDENT DEDENT / * Driver Code * / NEW_LINE N = 1667848271 NEW_LINE print ( key ( N ) ) NEW_LINE