Skip to content

Instantly share code, notes, and snippets.

@JenkinsDev
Last active March 29, 2016 15:12
Show Gist options
  • Save JenkinsDev/d13e7b5c71c396cfba0c to your computer and use it in GitHub Desktop.
Save JenkinsDev/d13e7b5c71c396cfba0c to your computer and use it in GitHub Desktop.
Reverse Number Without Strings In Python
# To the not-so-mathematically-inclined, this function may look like pure witch-
# craft. That's why I shall describe how it works.
#
# Let's say we start with an initial number of `13`, we expect an output of `31`,
# right? Let's see:
#
# reverse_number(13)
#
# num = 13
# reversed_num = 0
#
# first loop of while loop:
# reversed_num *= 10 (reversed_num = 0)
# reversed_num += num % 10 (reversed_num = 3; 13 % 10 = 3. % = modulus, remainder of divion)
# num /= 10 (num = 1; We remove the three because we extracted it above).
#
# second loop of while loop:
# reversed_num *= 10 (reversed_num = 30; 3 * 10 = 30)
# reversed_num += num % 10 (reversed_num = 31; 1 % 10 = 1)
# num /= 10 (num = 0; 1 / 10 = 0)
#
# Third loop doesn't happen because num is now zero. `reversed_num` now contains
# our fully reversed_number.
def reverse_number(num):
reversed_num = 0
while num != 0:
reversed_num *= 10
reversed_num += num % 10
num = int(num / 10)
return reversed_num
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment