您好,登录后才能下订单哦!
本篇文章为大家展示了使用Python怎么对整数进行反转,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 。请根据这个假设,如果反转后整数溢出那么就返回 0。
如果是正数:
tra = 0 while x != 0: n2 = x%10 x = x //10 tra = tra*10 + n2
如果是负数就abs()一下这个数
给出范围[−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 查?我也一样。时间一长,这让人厌倦。
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
上述内容就是使用Python怎么对整数进行反转,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。