demo/old/reverse_number.py

40 lines
580 B
Python

def reverse_num_as_int(x):
if x < 0:
neg = True
x = -x
else:
neg = False
while not (x % 10):
x //= 10
rev = 0
while x:
rev *= 10
rev += x % 10
x //= 10
if neg:
return -rev
else:
return rev
import re
def reverse_num_as_str(s):
if s[0] == '-':
neg = True
s = s[1:]
else:
neg = False
s = re.sub(r'^0*', '', s)
s = re.sub(r'0*$', '', s)
if neg:
return '-' + s[::-1]
else:
return s[::-1]