Python solution using simple Math


  • 0
    G

    The idea is to generate the reverse extracting the LSD from the given number.


    Example: num = 123

    Number Reverse
    1230
    123 / 10 = 120 * 10 + 3 = 3
    12 / 10 = 13 * 10 + 2 = 32
    1 / 10 = 032 * 10 + 1 = 321

    def reverse(int num):
      # Initializing the rev to 0
      rev = 0
      
      while num > 0:
        # Extracting the LSD using % 10 and adding it to the previous rev appropriately
        rev = rev * 10 + (num % 10)
        # Getting rid of the LSD
        num /= 10
    
    return rev
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.