00_coding_study

[leetcode] No 7. Reverse Integer python

for dream 2023. 2. 25. 22:56
반응형

[Problem]

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

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

 

[Solution]

It is quite simple problem. just reverse digits like [123 > -123]

In my case, I think int such as string.

 

So, int is converted to str using such as str(int).

There are two cases like positive and negative. I just check it in the first element.

 

After submitting, I found that there was a missing case that was reverse integer been smaller than 2^(-31) or larger than 2^31-1. As a result, I added the same code in the first line to the last line.

 

Finally, I passed! 

class Solution:
    def reverse(self, x: int) -> int:
        if x < -(2**31) or x > (2**31 - 1): return 0
        
        str_x = str(x)
        
        first_bit = 0
        start_num = 0
        num_str = len(str_x)
        
        if str_x[0] == '-':
            first_bit = 1
            start_num = 1
        
        ans = ''
        
        for i in range(num_str-1, start_num-1, -1):
            ans = ans + str_x[i]
        
        if first_bit == 1:
            ans = '-' + ans
        
        ans = int(ans)
        
        if ans < -(2**31) or ans > (2**31 - 1): return 0
        
        return ans
            

반응형