• leetcode415拓展字符串相加(带符号)


    1. class Solution:
    2. def addtoStrings(self,num1,num2):
    3. # 两个数字字符串相加的结果转为字符串
    4. i, j, add, res = len(num1)-1, len(num2)-1, 0, ''
    5. while i >= 0 or j >= 0 or add != 0:
    6. n1 = int(num1[i]) if i >= 0 else 0
    7. n2 = int(num2[j]) if j >= 0 else 0
    8. tmp = n1 + n2 + add
    9. # 借助除法和取余来得到进位和剩余位数的值
    10. add = tmp // 10
    11. res = str(tmp%10) + res
    12. i -= 1
    13. j -= 1
    14. return res
    15. def compare(self,num1,num2):
    16. # 比较num1和num2的大小 要求num1大于等于num2 这样判断方便后面做减法
    17. if len(num1) > len(num2):
    18. return True
    19. elif len(num2) > len(num1):
    20. return False
    21. else:
    22. # 二者相等 从高位开始比较
    23. for i in range(len(num1)):
    24. if int(num1[i]) < int(num2[i]):
    25. return False
    26. return True
    27. def minustoStrings(self,num1,num2):
    28. # 这里针对 num1大于等于num2的 两个数字字符串相减的结果转为字符串
    29. # num1 减 num2 的字符串结果
    30. i, j, minus, res = len(num1)-1, len(num2)-1, 0, ''
    31. while i >= 0:
    32. n1 = int(num1[i]) if i >= 0 else 0
    33. n2 = int(num2[j]) if j >= 0 else 0
    34. diff = n1 - n2 - minus
    35. if diff < 0:
    36. diff += 10
    37. minus = 1
    38. else:
    39. minus = 0
    40. res = str(diff) + res
    41. i -= 1
    42. j -= 1
    43. for i in range(len(res)):
    44. if res[i] != '0':
    45. return res[i:]
    46. return '0'
    47. def addStrings(self, num1, num2) :
    48. if num1[0] == '-' and num2[0] == '-':
    49. return '-' + self.addtoStrings(num1[1:],num2[1:])
    50. if num1[0] == '-':
    51. # 若num1 更大 则为负 若num2更大则为正
    52. if self.compare(num1[1:],num2):
    53. return '-' + self.minustoStrings(num1[1:],num2)
    54. else:
    55. return self.minustoStrings(num2,num1[1:])
    56. if num2[0] == '-':
    57. # 若num2 更大 则为负 若num1更大则为正
    58. if self.compare(num2[1:],num1):
    59. return '-' + self.minustoStrings(num2[1:],num1)
    60. else:
    61. return self.minustoStrings(num1,num2[1:])
    62. else:
    63. return self.addtoStrings(num1,num2)
    64. num1 = '53'
    65. num2 = '-3'
    66. a = Solution()
    67. print(a.addStrings(num1,num2))
  • 相关阅读:
    vue 中 watch 对对象的深度监听
    element ui tree树形控件实现单选操作
    08_Seata—分布式事务介绍
    框架安全-CVE 复现&Spring&Struts&Laravel&ThinkPHP漏洞复现
    【技术分享】NetLogon于域内提权漏洞(CVE-2020-1472)
    Android webView加载高德地图定位不显示问题
    RibbitMQ学习笔记之死信队列
    [ 漏洞复现篇 ] Apache Spark 命令注入(CVE-2022-33891)
    PHP:三元运算符
    变化数据捕获(CDC)技术分类优劣与适用场景
  • 原文地址:https://blog.csdn.net/cuier520/article/details/134488850