Python 實現反轉整數的案例(很容易懂的那種)

題目:

給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。

示例 1:

  輸入: 123

  輸出: 321   

示例 2:

  輸入: -123

  輸出: -321   

示例 3:

  輸入: 120

  輸出: 21

註意:

假設我們的環境隻能存儲得下 32 位的有符號整數,則其數值范圍為

。請根據這個假設,如果反轉後整數溢出那麼就返回 0。

解題思路:

1.實現數據的反轉

如果是正數:

tra = 0
while x != 0:
  n2 = x%10
  x = x //10
  tra = tra*10 + n2

如果是負數就abs()一下這個數

2.溢出判定

給出范圍[−2^31, 2^31 − 1]

則輸出的結果tra就必須滿足這個范圍.

代碼:

class Solution(object):
 def reverse(self, x):
 base = 1
 for i in range(31):
 base = base * 2
 two_Max = base - 1
 two_Min = -base
 tra = 0
 if x < 0:
 x = abs(x)
 while x != 0:
 n2 = x % 10
 if tra > abs(two_Min) // 10 or (tra == abs(two_Min) // 10 and n2 < -8):
  return 0
 x = x // 10
 tra = tra * 10 + n2
 return -tra
 else:
 while x != 0:
 n2 = x % 10
 if tra > two_Max//10 or (tra == two_Max and n2 > 7 ):
  return 0
 x = x // 10
 tra = tra * 10 + n2
 return tra

補充:python實現數字反轉_python 數字怎麼反轉

每次寫 Python 都會忘記該怎麼寫,最後隻能去 Stack Overflow 查?我也一樣。時間一長,這讓人厭倦。

這15個 Python 技巧和竅門,可以幫你提高效率

1. 交換值

x, y = 1, 2 
print(x, y) 
x, y = y, x 
print(x, y)

2. 字符串列表合並為一個字符串

sentence_list = ["my", "name", "is", "George"] 
sentence_string = " ".join(sentence_list) 
print(sentence_string)

3. 將字符串拆分為子字符串列表

sentence_string = "my name is George" 
sentence_string.split() 
print(sentence_string)

4. 通過數字填充初始化列表

[0]*1000 
# List of 1000 
zeros [8.2]*1000 
# List of 1000 8.2's

5. 字典合並

x = {'a': 1, 'b': 2} 
y = {'b': 3, 'c': 4} 
z = {**x, **y}

6. 反轉字符串

name = "George" name[::-1] 

7. 從函數返回多個值

def get_a_string(): 
a = "George" 
b = "is" 
c = "cool" return a, b, c 
sentence = get_a_string() (a, b, c) = sentence

8. 列表解析式

a = [1, 2, 3] 
b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2

9. 遍歷字典

m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for key, value in m.items(): print('{0}: {1}'.format(key, value))

10. 同時遍歷列表的索引和值

m = ['a', 'b', 'c', 'd'] for index, value in enumerate(m): print('{0}: {1}'.format(index, value))

11. 初始化空容器

a_list = list() 
a_dict = dict() 
a_map = map() 
a_set = set()

12. 刪除字符串兩端的無用字符

name = " George " name_2 = "George///" name.strip() # prints "George" name_2.strip("/") # prints "George"

13. 列表中出現最多的元素

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] print(max(set(test), key = test.count))

14. 檢查對象的內存使用情況

import sys x = 1 print(sys.getsizeof(x))

15. 將 dict 轉換為 XML

from xml.etree.ElementTree import Element def dict_to_xml(tag, d): ''' Turn a simple dict of key/value pairs into XML ''' elem = Element(tag) for key, val in d.items(): child = Element(key) child.text = str(val) elem.append(child) return elem

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: