Anonymous
Anonymous

Reputation: 37

Reversing the digits of a number in Python

I am writing a program in which I have to reverse a number using the below logic.

N = 321
enable_print = N % 10
while N > 0:
    if enable_print == 0:
        enable_print = 1 
    elif enable_print == 1:
        print(N % 10, end="")
    N = N // 10

This works great for numbers that do not have trailing zeroes. The problem arises when the number has trailing zeroes, for example:

when N = 32100, output = 0123

Is there an error in the code above, due to which I am not able to remove the first zero in the output?

Upvotes: 0

Views: 462

Answers (3)

Scott Hunter
Scott Hunter

Reputation: 49803

It seems more straight forward to eliminate the "leading" 0's first, and then you don't have to worry about them:

while N>0 and N % 10 == 0:
    N = N // 10
while N > 0:
    print(N % 10, end="")
    N = N // 10

Upvotes: 0

matszwecja
matszwecja

Reputation: 7971

the reverse string methods are all nice and clever, but I think pointing out the error in OP's code will be just as useful, if not more than providing completely different code snippet that does the same job.

You set enable_print to 1 in the first iteration, so you will never skip more than 1 trailing 0. You need to set it to 1 first time you encounter non 0 value.

N = 3002100

enable_print = False
while N > 0:
    if not enable_print:
        enable_print = (N % 10 != 0)
    if enable_print:
        print(N % 10, end="")
    N = N // 10

Upvotes: 1

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

Try with this:

print(int(str(N)[::-1]))

Upvotes: 0

Related Questions