Search code examples
stringpython-3.xintegerpalindrome

How to find the middle value of an integer without converting it to a string using Python3?


While solving the next smallest palindrome problem, I had to convert an integer to a string so I can reverse and find the middle value. There has to be a solution - how to find the middle value of an integer without converting it to a string using Python3? Appreciate your assistance. Thanks.

Examples:

  1. input=78653, result=6
  2. input=7564, result=5

Solution

  • This is a start.
    It needs some tweaking:

    import math
    
    def mid_digit(n):
    
        # num of digits
        a = math.trunc(math.log(n,10)+1)    
    
        # moving half of digits to the right of decimal point
        b = n / 10 ** round(a/2 + 0.5)
    
        # getting the left most decimal digit
        c = math.trunc(math.modf(b)[0] * 10) 
    
        return c