-1

I am solving leetcode problem 7 reverse integer

with condition Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Below is my code

class Solution:
    def reverse(self, x: int) -> int:
        if x
        val = 0
        pro, x = (1,x) if x>0 else (-1, -x)
        flag = False
        while x:
            val=val*10+x%10
            x//=10
            if val.bit_length()>31:
                flag = True
                break
        return 0 if flag else val*pro

code work fine and solve this challenge.

But i am still in doubt and it is related to integer overflow.

considering a strict environment 32 bit, where we need to reverse a number in that range, so if we have a reverse of a number which doesn't fit in 32 bit range, so it will get outflow or not stored(don't know correct terminology, correct me here) so how can we check that part ?

in simple term (i assume), in 32 bit system val.bit_length() should be restrict to 31 bits and new int which is adding to the val doesn't add any value to it and it remain same.

sahasrara62
  • 10,069
  • 3
  • 29
  • 44

1 Answers1

0

To be honest it's a bit hard to understand what are you asking for. Python's ints are stored on a heap (at least in CPython), which means there is no int size limit as long as there is enough space to store it. It's implemented internally. See How does Python manage int and long? Although if you need real int32, you can get it from mypy library.

In comparison, in C int is fixed. In case you try to store a value out of boundaries the integer overflow will occur. The C standard defines this situation as undefined behavior (meaning that anything might happen).

funnydman
  • 9,083
  • 4
  • 40
  • 55