Dwight schrute
Dwight schrute

Reputation: 11

reverse a number in python looking for debugging

Hi I have the code for reversing a number, I am a beginner for python?

I dont know why is not working, thanks for your help.

class Solution(object):
    def revint(self, number):
        while(number>0):
            reverse=0
            reminder=0
            reverse=(reverse*10)+reminder
            number=number//10 
        return reverse
revint(123)

Upvotes: 0

Views: 153

Answers (3)

Soumya Ranjan Rout
Soumya Ranjan Rout

Reputation: 413

You have initiated a variable reverse=0 in side while loop, so the variable is not reachable to return statement.

def reverse_a_number(number: int) -> int:
    reverse = 0
    while number > 0:
        remainder = number % 10
        reverse = (reverse * 10) + remainder
        number = number // 10
    return reverse



rev = reverse_a_number(123456)
print(rev)

Output:

654321

Upvotes: 0

abarnert
abarnert

Reputation: 366093

Your first problem is here:

revint(123)

There is no revint function to call. You've defined a revint method, on the Solution class. So, you need to construct an instance, so you can call its methods:

solution = Solution()
solution.revint(123)

You also need to do something with the result of that method, not just ignore it:

print(solution.revint(123))

Next:

    while(number>0):
        reverse=0

You're resetting reverse to 0 each time through the loop. So, you add a digit, then throw it away and start at 0 again, then add another digit, and so on. So you're going to end up with just the last digit.

You only way to set it to 0 once, at the start:

    reverse=0
    while(number>0):

Next:

    reminder = 0

This is apparently supposed to be the remainder of dividing number by 10. But if you want that, you have to say so. Either:

    remainder = number % 10

… or, together with the division:

    number, remainder = divmod(number, 10)

Upvotes: 1

Addison Lynch
Addison Lynch

Reputation: 685

You could simply:

def revint(number):
    return int(str(number)[::-1])

Upvotes: 2

Related Questions