zoukankan      html  css  js  c++  java
  • Datawhale编程实践(LeetCode 腾讯精选练习50)Task6

    1.字符串相乘https://leetcode-cn.com/problems/multiply-strings/

    学到了for i in range(a, b, c)的用法,其中c为步长

    复习了python 字符串的各种操作

    对这题的要求和答案不是很理解,要求不能直接将输入转换为整数来处理,但是答案也只是将字符串的每一位字符转换为整数来处理,后面还是有点理解了题目的用意

     1 class Solution:
     2     def multiply(self, num1: str, num2: str) -> str:
     3         if num1 == "0" or num2 == "0":
     4             return "0"
     5         
     6         ans = "0"
     7         m, n = len(num1), len(num2)
     8         for i in range(n - 1, -1, -1):
     9             add = 0
    10             y = int(num2[i])
    11             curr = ["0"] * (n - i - 1)
    12             for j in range(m - 1, -1, -1):
    13                 product = int(num1[j]) * y + add
    14                 curr.append(str(product % 10))
    15                 add = product // 10
    16             if add > 0:
    17                 curr.append(str(add))
    18             curr = "".join(curr[::-1])
    19             ans = self.addStrings(ans, curr)
    20         
    21         return ans
    22     
    23     def addStrings(self, num1: str, num2: str) -> str:
    24         i, j = len(num1) - 1, len(num2) - 1
    25         add = 0
    26         ans = list()
    27         while i >= 0 or j >= 0 or add != 0:
    28             x = int(num1[i]) if i >= 0 else 0
    29             y = int(num2[j]) if j >= 0 else 0
    30             result = x + y + add
    31             ans.append(str(result % 10))
    32             add = result // 10
    33             i -= 1
    34             j -= 1
    35         return "".join(ans[::-1])

     乘法解就是用一个数组存储每一位的乘积(可能有两位数),然后再进行进位运算

     1 class Solution:
     2     def multiply(self, num1: str, num2: str) -> str:
     3         if num1 == "0" or num2 == "0":
     4             return "0"
     5         
     6         m, n = len(num1), len(num2)
     7         ansArr = [0] * (m + n)
     8         for i in range(m - 1, -1, -1):
     9             x = int(num1[i])
    10             for j in range(n - 1, -1, -1):
    11                 ansArr[i + j + 1] += x * int(num2[j])
    12         
    13         for i in range(m + n - 1, 0, -1):
    14             ansArr[i - 1] += ansArr[i] // 10
    15             ansArr[i] %= 10
    16         
    17         index = 1 if ansArr[0] == 0 else 0
    18         ans = "".join(str(x) for x in ansArr[index:])
    19         return ans

    2.全排列https://leetcode-cn.com/problems/permutations/

    3.最大子序和https://leetcode-cn.com/problems/maximum-subarray/

  • 相关阅读:
    实验6:Mapreduce实例——WordCount
    暑期生活10
    暑期生活9
    暑期生活8
    暑期生活7
    暑期生活6
    暑期生活5
    暑期生活4
    暑期生活3
    暑期生活2
  • 原文地址:https://www.cnblogs.com/zmbreathing/p/datawhale_leetcode_task6.html
Copyright © 2011-2022 走看看