您好,登錄后才能下訂單哦!
本篇文章為大家展示了使用Python怎么對整數(shù)進行反轉(zhuǎn),內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
給出一個 32 位的有符號整數(shù),你需要將這個整數(shù)中每位上的數(shù)字進行反轉(zhuǎn)。
示例 1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設(shè)我們的環(huán)境只能存儲得下 32 位的有符號整數(shù),則其數(shù)值范圍為 。請根據(jù)這個假設(shè),如果反轉(zhuǎn)后整數(shù)溢出那么就返回 0。
如果是正數(shù):
tra = 0 while x != 0: n2 = x%10 x = x //10 tra = tra*10 + n2
如果是負數(shù)就abs()一下這個數(shù)
給出范圍[?2^31, 2^31 ? 1]
則輸出的結(jié)果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實現(xiàn)數(shù)字反轉(zhuǎn)_python 數(shù)字怎么反轉(zhuǎn)
每次寫 Python 都會忘記該怎么寫,最后只能去 Stack Overflow 查?我也一樣。時間一長,這讓人厭倦。
x, y = 1, 2 print(x, y) x, y = y, x print(x, y)
sentence_list = ["my", "name", "is", "George"] sentence_string = " ".join(sentence_list) print(sentence_string)
sentence_string = "my name is George" sentence_string.split() print(sentence_string)
[0]*1000 # List of 1000 zeros [8.2]*1000 # List of 1000 8.2's
x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = {**x, **y}
name = "George" name[::-1]
def get_a_string(): a = "George" b = "is" c = "cool" return a, b, c sentence = get_a_string() (a, b, c) = sentence
a = [1, 2, 3] b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for key, value in m.items(): print('{0}: {1}'.format(key, value))
m = ['a', 'b', 'c', 'd'] for index, value in enumerate(m): print('{0}: {1}'.format(index, value))
a_list = list() a_dict = dict() a_map = map() a_set = set()
name = " George " name_2 = "George///" name.strip() # prints "George" name_2.strip("/") # prints "George"
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] print(max(set(test), key = test.count))
import sys x = 1 print(sys.getsizeof(x))
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
上述內(nèi)容就是使用Python怎么對整數(shù)進行反轉(zhuǎn),你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。