0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LeetCode : 7. Reverse Integerの解法

Posted at

初めに

本日もLeetCodeやってまいります。
今回は以下の問題。

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).

 

Example 1:

Input: x = 123
Output: 321
Example 2:

Input: x = -123
Output: -321
Example 3:

Input: x = 120
Output: 21
 

Constraints:

-231 <= x <= 231 - 1

回答

class Solution:
    def reverse(self, x: int) -> int:
        result_str = ""
        if x < 0:
            for digit in str(abs(x))[::-1]:
                if digit == 0:
                    continue
                result_str += digit
            if -2**31 > -int(result_str):
                return 0
            return -int(result_str)
        if x >= 0:
            for digit in str(x)[::-1]:
                if digit == 0:
                    continue
                result_str += digit
            
            if int(result_str) > 2**31 - 1:
                return 0
            return int(result_str)

これだとちょっと長いのでGPTにシンプルにしてもらいました笑

class Solution:
    def reverse(self, x: int) -> int:
        sign = -1 if x < 0 else 1
        s = str(abs(x))[::-1]
        result = sign * int(s)
        if result < -2**31 or result > 2**31 - 1:
            return 0
        return result

最後に

無駄なループ書きすぎてました涙
これからも精進します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?