Absolute difference between the first X and last X Digits of N | Function to find the number of digits in the integer ; Function to find the absolute difference ; Store the last x digits in last ; Count the no . of digits in N ; Remove the digits except the first x ; Store the first x digits in first ; Return the absolute difference between the first and last ; Driver code
def digitsCount ( n ) : NEW_LINE INDENT length = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT length += 1 ; NEW_LINE n //= 10 ; NEW_LINE DEDENT return length ; NEW_LINE DEDENT def absoluteFirstLast ( n , x ) : NEW_LINE INDENT i = 0 ; NEW_LINE mod = 1 ; NEW_LINE while ( i < x ) : NEW_LINE INDENT mod *= 10 ; NEW_LINE i += 1 ; NEW_LINE DEDENT last = n % mod ; NEW_LINE length = digitsCount ( n ) ; NEW_LINE while ( length != x ) : NEW_LINE INDENT n //= 10 ; NEW_LINE length -= 1 ; NEW_LINE DEDENT first = n ; NEW_LINE return abs ( first - last ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 21546 ; NEW_LINE x = 2 ; NEW_LINE print ( absoluteFirstLast ( n , x ) ) ; NEW_LINE DEDENT