iT邦幫忙

2021 iThome 鐵人賽

DAY 3
0
自我挑戰組

30天 Leetcode解題之路系列 第 3

Day 3 - Reverse Integer

Day 3 - Reverse Integer

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~


7. Reverse Integer

Question

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 [-2^31, 2^31 - 1], then return 0.

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


Example

Example1

Input: x = 123
Output: 321

Example2

Input: x = -123
Output: -321

Example3

Input: x = 120
Output: 21

Example4

Input: x = 0
Output: 0

Constraints

  • -2^31 <= x <= 2^31 - 1

解題

題目

首先先簡單的翻譯一下題目
給一個32-bit的有號整數x,把這個x顛倒過來,並回傳顛倒過後的x。如果顛倒過後的x的值的範圍不在-2^31 <= x <= 2^31 - 1,則回傳0。

Think

想法是這樣,先不管他正負號,先把他轉成str的型態,就可以得到每一個位數的數字。接著,因為要顛倒過來,所以位數是會愈來愈大,從10^1, 10^2, 10^3, ...10^n。

作法大致上是這樣

  • ver. 1
    • rev存最後的結果,multiple是用來算目前10的次方是幾次。
    • 在補上判斷是否超過範圍的if判斷式,就完工啦~
  • 後來想想好像可以不用乘法的方式(ver. 2)。
  • ver. 2
    • rev也是存最後的結果,只是不用乘法,改用list的型態,將鏡像位址的元素交換,再轉回數字,中間有一行有一堆replace是為了把list轉str時,不需要的字串去掉。
  • 但是結果發現好像沒有比較快XD。

Code

Python

ver. 1
class Solution:
    def reverse(self, x: int) -> int:
        rev = 0
        multiple = 0
        
        if x < 0:
            str_x = str(-x)
        else:
            str_x = str(x)
            
        for index in range(len(str_x)):
            rev += int(str_x[index])*(10**multiple)
            multiple += 1
            
        if x < 0:
            rev = -rev
            
        if (-2**31) > rev or rev > (2**31-1):
            rev = 0
            
        return rev
ver. 2
class Solution:
    def reverse(self, x: int) -> int:
        rev = 0
   
        if x < 0:
            list_x = list(str(-x))
        else:
            list_x = list(str(x))
        print(list_x)
        for index in range(len(list_x)):
            list_x[index], list_x[len(list_x)-index-1] = list_x[len(list_x)-index-1], list_x[index]

            if (index-(len(list_x)-index-1)) == 0 or ((index+1) == (len(list_x)-index-1) and index == (len(list_x)-index-1)-1):
                break

        rev_str = str(list_x).replace(" ", "").replace(",", "").replace("[", "").replace("]", "").replace("'", "")
        
        if x < 0:
            rev = -int(rev_str)
        else:
            rev = int(rev_str)
            
        if (-2**31) > rev or rev > (2**31-1):
            rev = 0
    

C

int reverse(int x){
    long int rev = 0;
    
    while(x != 0){
        rev *= 10;
        rev += (x%10);
        
        x = x/10;
    }
    
    // INT_MIN: -2^31 = -2147483647-1
    // INT_MAX: 2^31-1 = 2147483647
    return (rev < INT_MIN || rev > INT_MAX)? 0 : rev;
}

Result

  • Python

    • ver. 1
    • ver. 2
  • C

大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 2 - Two Sum
下一篇
Day 4 - Remove Duplicates from Sorted Array
系列文
30天 Leetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言