Python_Leetcode_7_整數反轉

1.背景

Leetcode專欄目的:希望給學習算法的朋友提供一些想法,也希望有大佬能夠通過評論提供寶貴的意見。

Leetcode專欄方式:將展示實現代碼的多種實現方式,並且對算法複雜度進行比較。由於筆者偏好,代碼全部使用python實現。

本期題目: https://leetcode-cn.com/problems/reverse-integer/
在這裏插入圖片描述
在這裏插入圖片描述

2.解題方式

本次介紹循環、字符串反轉兩種解題方式

2.1 循環

本方法採用flag進行正負數標記,利用循環進行數值反轉。

class Solution:
    def reverse(self, x: int) -> int:
        flag = (x > 0 and 2 or 1)
        x = (flag == 1 and -x or x)
        result = 0
        while x:
            result *= 10
            result += x % 10
            x //= 10
        result = (-1)**flag*result

        if result > 2147483647 or result < -2147483648:
            return 0
        return result

2.2 字符串反轉

字符串反轉方法是先用flag標記數值正負,然後統一用正數進行字符串反轉,再利用flag進行正負還原。

class Solution:
    def reverse(self, x: int) -> int:
        flag = (x > 0 and 2 or 1)
        x = (flag == 1 and str(-x)[::-1] or str(x)[::-1])
        x = (flag == 1 and -1*int(x) or int(x))

        if x > 2147483647 or x < -2147483648:
            return 0
        return x

在這裏插入圖片描述

3.總結

這個題目我在某大廠二面的過程中遇到過,題目很簡單,在後期交流的過程中得知出彩點在於:

  • 考慮到兩種解題思路,實際上還可以有遞歸的方式,這不做解釋,感興趣可以自己實現。
  • if-else語句使用很靈活。

因此在這總結一些簡單易理解的if-else變化:

普通寫法:這種寫法在簡單的if-else是表現得過於囉嗦

if a>b:
    c = a
else:
    c = b

表達式:真時放if前,這種可讀性比較好

c = a if a>b else b

二維列表:利用大小判斷的0,1當作索引。這種思路比較好,但是實踐上效果一般

c= [b, a][a > b]

邏輯運算符:雖然簡單,卻發揮無限能量。

c = (a>b and a or b)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章