LeetCode 刷题记录(6-10题)
6 Z 字形变换(题目链接)
class Solution: def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ lists = [] for i in range(numRows): lists.append('') numMids = numRows - 2 if numMids < 0: numMids = 0 for i_s in range(len(s)): rest = i_s % (numMids + numRows) if rest < numRows: lists[rest] = ''.join([lists[rest], s[i_s]]) else: lists[numMids + numRows - rest] = ''.join([lists[numMids + numRows - rest], s[i_s]]) s_result = ''.join(lists) return s_result
7.整数反转(题目链接)
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ y = 0 z = 1 if x < 0: z = -1 x = -x while x != 0: item = x % 10 x = x // 10 if 2147483647 - 10 * y <= item: return 0 y = y * 10 + item return y*z
8.字符串转换整数 (atoi)(题目链接)
class Solution: def myAtoi(self, str: 'str') -> 'int': sign = 0 num = 0 for i in str: if sign == 0 and i == ' ': continue elif sign == 0 and i == '-': sign = -1 elif sign == 0 and i == '+': sign = 1 elif i in ['0','1','2','3','4','5','6','7','8','9']: if (sign == 1 or sign == 0) and (2147483647 - int(i)) // 10 < num: return 2147483647 elif sign == -1 and (2147483648 - int(i)) // 10 < num: return -2147483648 else: if sign == 0: sign = 1 flag = 1 num = num * 10 + int(i) else: break if sign == 0: return num return sign * num