I wrote a code that reverses a given integer in Python. The expected inputs and outputs are as follows:
(1)
Input: 123
Output: 321
(2)
Input: -123
Output: -321
def reverse(num):
result = 0
repeat = len(str(num))
original_num = num
if original_num < 0:
num *= -1
else:
pass
for i in range(repeat):
mod = num % 10
num //= 10
result = result * 10 + mod
if original_num < 0:
result *= -1
return result
When the input is positive, the output is as I expected. But when the input is negative, the result adds an unexpected 0 to the end of the output, so when the input is -123
, the output is -3210
.
Can somebody tell me where this error is coming from?
Seems like you overshoot in:
for i in range(repeat):
This is much easier:
def rev( num ) :
digits = ''.join( [i for i in str(num) if i in '0123456789'] )
maybe_sign = str(num).replace( digits, '')
return int(maybe_sign + ''.join( reversed(digits) ))
The result:
>>> rev(123)
321
>>> rev(-123)
-321
You have set repeat = len(str(num))
before changing the sign of negative numbers and you should decrement it if num is negative. In your last iteration of for
loop (if num is negative), mod
will be always zero and hence, you will always get a zero appended if num is negative.
If I would be solving this problem, then I might have written it in this way:
def reverse(num):
sign = num >= 0 # True if num is +ve. False if num is -ve
num = abs(num)
repeat = len(str(num))
result = 0
for i in range(repeat):
mod = num % 10
num //= 10
result = result * 10 + mod
return result if sign else -result
print(reverse(123))
print(reverse(-123))
There is another way to solve this problem which is bit more compact:
def revdigits(num):
reverseStr = lambda s: "".join(reversed(s))
digits = reverseStr(str(num)) if num >= 0 else ("-" + reverseStr(str(num)[1:]))
return int(digits)
num = 123
print(revdigits(num))
print(revdigits(-num))
Output:
321
-321
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With