marshallslee
marshallslee

Reputation: 655

Reversing a negative integer results in an unexpected result

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?

Upvotes: 5

Views: 908

Answers (7)

Kailash Hiwrale
Kailash Hiwrale

Reputation: 1

I think this one is the simplest way to get negative and positive integers reversed:

def reversenumber(n):
    factor = -1 if n < 0 else 1
    n = abs(n)
    rev = 0
    while n > 0:
        a = n % 10
        rev = rev * 10 + a
        n = n // 10
    return rev * factor

reversenumber(-123456)

Output = -654321

Upvotes: 0

Georgina Skibinski
Georgina Skibinski

Reputation: 13407

I think you are overcomplicating it, this should do the trick for you:

def reverse(num):
    res=int(str(abs(num))[::-1])
#simplifies your for loop to get back the zeros at the end:
    res*=10**(len(str(abs(num)))-len(str(res)))
    if(num<0): res=-res
    return res

Upvotes: 0

abhiarora
abhiarora

Reputation: 10460

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

Upvotes: 1

codrelphi
codrelphi

Reputation: 1065

In your code, you just have to set the repeat variable after testing that the original_num is negative. See the code below.

def reverse(num):
    result = 0
    original_num = num
    if original_num < 0:
        num *= -1
    repeat = len(str(num))
    for i in range(repeat):
        mod = num % 10
        num //= 10
        result = result * 10 + mod
    if original_num < 0:
        result *= -1
    return result

print(reverse(123))   # 321
print(reverse(-123))  # -321

Upvotes: 0

Samay Gupta
Samay Gupta

Reputation: 437

This seems to be happening as the length for iterations is taken before converting to a positive value. That's why the '-' sign is taken while calculating the result which gives an extra 0. The corrected code would be

def reverse(num):
    result = 0
    original_num = num
    if original_num < 0:
        num *= -1
    else:
        pass
    repeat = len(str(num))
    for i in range(repeat):
        mod = num % 10
        num //= 10
        result = result * 10 + mod

    if original_num < 0:
        result *= -1
    return result

print(reverse(-123))

A simpler solution:

def reverse(num):
    factor = -1 if num < 0 else 1
    num = abs(num)
    res = 0
    for i in range(len(str(num))-1, -1, -1):
        res += (10**i)*(num%10)
        num //= 10
        print(res, num, i)
    return res*factor

print(reverse(-100))

If you're fine with using strings to reverse the value:

def reverse(num):
    return int(('-' if num<0 else '') + str(abs(num))[::-1])
print(reverse(-100))

Upvotes: 0

lenik
lenik

Reputation: 23556

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

Upvotes: 3

Strange
Strange

Reputation: 1550

This thing works:

x = -123

if x<0:
    x*=-1
    x = int(str(x)[::-1])
    x *=-1
else:
    x = int(str(x)[::-1])

print(x)

output

-321

Upvotes: 0

Related Questions