美文网首页
字符串相乘

字符串相乘

作者: 水瓶鱼 | 来源:发表于2017-03-15 23:57 被阅读15次

题目

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

python

  class Solution(object):
      def function(self,num1, num2):
          if num2 == 0:
              return '0'
          increase = 0
          result = ''
          length = len(num1) - 1
          while length >= 0:
              tem = int(num1[length]) * num2 + increase
              increase = tem // 10
              result = str(tem % 10) + result
              length -= 1
            if increase > 0:
              result = str(increase) + result
          return result


      def add(self,num1, num2):
          result = ''
          length1 = len(num1) - 1
          length2 = len(num2) - 1
          increase = 0
          while length1 >= 0 and length2 >= 0:
              tem = int(num2[length2]) + int(num1[length1]) + increase
              increase = tem // 10
              result = str(tem % 10) + result;
              length1 -= 1
              length2 -= 1
          if length1 < 0:
              length1 = length2
              num1 = num2
          while length1 >= 0:
              tem = int(num1[length1]) + increase
              increase = tem // 10
              result = str(tem % 10) + result;
              length1 -= 1
          if increase > 0:
              result = str(increase) + result;
          return result


      def multiply(self, num1, num2):
          """
          :type num1: str
          :type num2: str
          :rtype: str
          """
          if num1 == '0' or num2 == '0':
              return '0'
          result = '0'
          length = len(num2)
          for i in range(length):
              tem = self.function(num1, int(num2[length - 1 - i]))
              result = self.add(result, tem + '0' * i)
          return result

相关文章

  • Python3的字符串使用

    字符串可以相加,相乘

  • 字符串相乘

    题目 Given two non-negative integers num1 and num2 represen...

  • 字符串相乘

    给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示...

  • 字符串相乘

    题目描述:给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的...

  • 字符串相乘

    给定两个以字符串形式表示的非负整数 num1 和 num2 ,返回 num1 和 num2 的乘积,它们的乘积也表...

  • 字符串相乘

    字符串相乘   在 Python 语言中,算术运算符的“+”和“*”是可以对字符串进行操作的,如字符串拼接(str...

  • LeetCode:字符串相乘

    字符串相乘 - LeetCode[https://leetcode-cn.com/problems/multipl...

  • python的数据类型——字符串

    生成字符串 Python中可以使用一对单引号''或者双引号""生成字符串。 简单操作 加法: 字符串与数字相乘: ...

  • 字符串 大数相乘

    https://leetcode-cn.com/explore/interview/card/bytedance/...

  • LeetCode 43. 字符串相乘 | Python

    43. 字符串相乘 题目来源:力扣(LeetCode)https://leetcode-cn.com/proble...

网友评论

      本文标题:字符串相乘

      本文链接:https://www.haomeiwen.com/subject/ugxdnttx.html