1

I am working through a coding challenge where I have to reverse an integer. If the integer has only 1 digit, I return the integer as it is. If its less than zero, I reverse it but keep the sign intact. I have to check for integer overflow to make sure that it is in the range [−231, 231 − 1]. The following is my code:

def reverse(self, x: int) -> int:
    
    if x >=0 and x <= 9:
        return x
    
    elif x > 9 and x < (2**31):
        rever1 =  str(x)[::-1]
        return int(rever1)
    
    elif x < 0 and x > (-2**31):
        rever2 = str(x)[::-1]
        rever2 = rever2[:-1]
        rever2 = -1  * int(rever2)
        return rever2
    
    elif x <= (-2**31) or x >= (2**31):
        return 0

I know how to make this code shorter so the inefficiency is fine for now. I just want to know why my code fails for 1534236469.

As much as I appreciate all help, it helps me more if you just tell me why the code fails instead of giving me a quick solve. The whole point behind these challenges is to learn so it defeats the purpose if someone just puts the answer.

3
  • What is self? Commented Nov 19, 2020 at 5:31
  • Could this be because the reversed integer would be greater than 2**31-1? Commented Nov 19, 2020 at 5:32
  • @Stef, this is how Leetcode structures answers. It has to be a method of a class Solution. Commented Nov 19, 2020 at 5:33

1 Answer 1

4

You check the input value, rather than the return value. The test case you give is the "problem" class: the input number is in range, but the reverse is not.

You need to check rever1 for being in range, as well:

elif x > 9 and x < (2**31):
    rever1 = str(x)[::-1]
    return int(rever1)

Could be

elif x > 9 and x < (2**31):
    rever1 = str(x)[::-1]
    if rever1 < (2**31):
        return int(rever1)
    else:
        return 0

Since you're planning to shorten the code appropriately, I won't go into those details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.