鱼C论坛

 找回密码
 立即注册
查看: 2899|回复: 0

[学习笔记] Leetcode 415. Add Strings

[复制链接]
发表于 2020-8-4 23:03:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

  2. Note:

  3. The length of both num1 and num2 is < 5100.
  4. Both num1 and num2 contains only digits 0-9.
  5. Both num1 and num2 does not contain any leading zero.
  6. You must not use any built-in BigInteger library or convert the inputs to integer directly.
复制代码

  1. class Solution:
  2.     def addStrings(self, num1: str, num2: str) -> str:
  3.         i, j = len(num1) - 1, len(num2) - 1
  4.         carry = 0
  5.         total = 0
  6.         result = ''
  7.         while i >= 0 or j >= 0:
  8.             total = carry
  9.             if i >= 0:
  10.                 total += ord(num1[i]) - 48
  11.             if j >= 0:
  12.                 total += ord(num2[j]) - 48
  13.             result += str(total % 10)
  14.             carry = total // 10
  15.             i -= 1
  16.             j -= 1
  17.         if carry > 0:
  18.             result += str(carry)
  19.         return result[::-1]
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-8 20:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表