반응형
[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 |
반응형
'00_coding_study' 카테고리의 다른 글
[leetcode] No 33. Search in Rotated Sorted Array Python (0) | 2023.03.05 |
---|---|
[leetcode] No 28. Find the Index of the First Occurrence in a String (python3) (0) | 2023.02.26 |
[leetcode] No 15. 3Sum python (0) | 2023.02.26 |
[leetcode] No 6. Zigzag Conversion Python (0) | 2023.02.20 |
[LeetCode] No 5. Longest Palindromic Substring (0) | 2023.02.19 |