LeetCode07:整数反转
Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment that could only store integers
within the 32-bit signed integer range: [−231, 231 − 1].
For this problem, assume that your function returns 0 when the reversed integer overflows.
一个很巧妙的解决方法,利用了python的切片方法。出自用python手刃Leetcode(7):反转整数【简单题】,文中还有提供另一种常规解法,感兴趣可以去看看。
class Solution:
def reverse(self, x):
flag = 1
if x < 0:
flag = -1
x = -x
R = str(x)[::-1]
R = int(R)
if R> 2147483647 or R < -2147483648:
R = 0
return R*flag
LeetCode08:字符串转换为整数
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer
(similar to C/C++'s atoi function).
The algorithm for myAtoi(string s) is as follows:
Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is '-' or '+'.
Read this character in if it is either. This determines if the final result is negative or positive respectively.
Assume the result is positive if neither is present.
Read in next the characters until the next non-digit charcter or the end of the input is reached.
The rest of the string is ignored.
Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32).
If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-231, 231 - 1],
then clamp the integer so that it remains in the range.
Specifically, integers less than -231 should be clamped to -231,
and integers greater than 231 - 1 should be clamped to 231 - 1.
Return the integer as the final result.
Note:
Only the space character ' ' is considered a whitespace character.
Do not ignore any characters other than the leading whitespace
or the rest of the string after the digits.
解决方案出自LeetCode-python 8.字符串转换整数 (atoi),但是文中代码s = str.strip()
有一点小错误,已经改正s = s.strip()
。
class Solution(object):
def myAtoi(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
if not s:
return 0
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
elif s[0]=='+':
s = s[1:]
num = ''
for c in s:
if c.isdigit():
num += c
else:
break
if not num:
return 0
num = int(num)*sign
INT_MAX = 2**31
return min(max(num,-1*INT_MAX), INT_MAX-1)
LeetCode09:回文数
Determine whether an integer is a palindrome.
An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
利用python切片得到代码最简洁的解决方案(并不意味着时间和空间最优),解决方案出自Python实现-LeetCode(0009)-回文数(简单)。这篇文章提供了非常全面的多种解决方案,并对题目的进阶问题提供了解决方案。
class Solution:
def isPalindrome(self, x: int) -> bool:
return True if str(x) == str(x)[::-1] else False
DataWhale任务链接:
team-learning-program/LeetCodeTencent/007 整数反转.md
team-learning-program/LeetCodeTencent/008 字符串转换整数 (atoi).md
team-learning-program/LeetCodeTencent/009 回文数.md