1、
思路是将数字转换为字符串进行倒置处理然后再转换为数字,注意转置后数值是否超出范围即可
beat 85%, 贴上代码:
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ _x = str(abs(x)) reversedX = int(_x[::-1]) if -(2**31)-1 < reversedX < 2**31: return reversedX if x >= 0 else -reversedX else: return 0
2、
思路是先strip()处理两端的空格,然后循环判断字符串中的字符是否是数字isdigit(),不是则停止循环且记录位置,
然后将截取到的字符串转换为int
beat 93%, 贴上代码:
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ _str = str.strip() if not _str or (_str[0] not in ['+', '-'] and not _str[0].isdigit()): return 0 flag = 0 for i, x in enumerate(_str): if i != 0 and not x.isdigit(): break flag = i if flag == 0 and _str[0] in ['+', '-']: return 0 value = int(_str[0:flag+1]) return max(-2**31, min(value,2**31-1))
3、
上周做的一道最长回文截取字符串题目,在里面其实已经完成这道题(写了一个判断是否是回文字符串的函数),
所以这里只需将数字转换为字符串,然后进行回文判断即可(判断方法是将字符串对半分,然后转置其中的一个,再判断是否相等)
beat 98%,贴上代码:
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False s = str(x) length = len(s) halfLength = length / 2 if length % 2 == 1: right = s[halfLength + 1:] return s[0:halfLength] == right[::-1] else: right = s[halfLength:] return s[0:halfLength] == right[::-1]
4、
思路是用Python的re库帮助判断,需在提供的正则表达式后面加上'$'以进行全文匹配(偷懒写法)。beat 43%,代码:
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ import re p = '^' + p +'$' groups = re.match(p, s) return True if groups else False
5、
思路是运用位操作循环对被除数进行扣除,直到不再大于除数,beat 44%,代码:
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ _dividend = abs(dividend) _divisor = abs(divisor) ret = 0 if _divisor == 1: ret = _dividend else: while(_dividend >= _divisor): temp, i = _divisor, 1 while _dividend >= temp: _dividend -= temp ret += i i <<= 1 temp <<= 1 if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0): ret = -ret return min(max(-2147483648, ret), 2147483647)