当前位置:网站首页>Leetcode 989. 数组形式的整数加法(简单)
Leetcode 989. 数组形式的整数加法(简单)
2022-06-27 17:57:00 【我是胖虎啊】
Leetcode 989. 数组形式的整数加法(简单)
题目链接
https://leetcode-cn.com/problems/add-to-array-form-of-integer/
思路讲解
官方示例: 输入:A = [1,2,0,0], K = 34 输出:[1,2,3,4] 解释:1200 + 34 = 1234
我一开始就根据题目示例中的思路去想, 然后写出了解法一
解法一:
1.将 数字型数组 -> 字符串型数组
2.将数组中的字符串拼接, 用eval函数取出字符串中的数字 和 k 取和,然后转为字符串
3.将字符串 -> 数字型的数组
code for python
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
list_str = [str(i) for i in num]
final_str = str(eval("".join(list_str)) + k)
return [int(j) for j in final_str]
复杂度分析
- 时间复杂度: O(N)
- 空间复杂度: O(N)
python的相关知识
- 关键字eval用来提取字符串中的表达式, 然后返回表达式的值. 示例:
print(eval("[1, 2, 3]")) # [1, 2, 3]
print(eval("pow(2, 3)")) # 8
其中pow(2, 3)的意思是计算2的3次方,结果为 8
- 列表推导式
print([i for i in range(5)]) # [0, 1, 2, 3, 4]
这样写法相当于:
arr = []
for i in range(5):
arr.append(i)
print(arr)
- 数组 -> 字符串(join的用法)
a = ['1', '2', '3', '4']
print("".join(a)) # 1234上面的解法一其实是一种取巧的做法, 正规的做法应该是用 进制的思路 去做,如解法二.此解法是从题解中看到的, 按照大佬的思路理了一下
解法二
题目思路
本题思路可类比2数相加的竖式计算(满10进1), 使用的算法思想是双指针法 !
1.定义2个指针, 分别指向 num 和 k 的末尾
2.从后往前遍历,只要最长的字符串有值就一直遍历.遍历过程中,如果较短的 字符串 or 列表 无对应索引, 则用数值0代替
3.最后判断一下carry变量,如果carry > 0,代表需要手动添加一次1(因为可能上面的最后一次判断中,carry>0,然后循环就终止了)
code for python
from typing import List
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
len_num = len(num) - 1
len_k = len(str(k)) - 1
arr = []
carry = 0 # 是否需要进一位的标识符
while len_num >= 0 or len_k >= 0:
x = num[len_num] if len_num >= 0 else 0
y = int(str(k)[len_k]) if len_k >= 0 else 0
total = x + y + carry
carry = total // 10
arr.append(total % 10)
len_num -= 1
len_k -= 1
if carry:
arr.append(1)
return arr[::-1]
复杂度分析
- 时间复杂度: O(N)
- 空间复杂度: O(1)
python的相关知识
- 列表翻转
a = [1, 2, 3, 4]
方式1:
print(a[::-1]) # 本题使用的翻转方法
方式2:
a.reverse() # 注意使用reverse,更改的是原数组中元素的顺序!
print(a)
方式3:
print(list(reversed(a))) # ['4', '3', '2', '1']
# 注意reversed的结果是一个 迭代器 对象, 需要使用list()函数转为列表
print(a) # ['1', '2', '3', '4'] # 使用reversed不会影响到原来的列表
- 取余 + 获取除数
# 取余数
a = 12
print(a % 10) # 2
知识点:
//表示整数除法
/表示 浮点数除法,返回浮点结果
# 获取除数(整数): //
b = 25
print(25//4) # 6
# 获取除数(浮点数): /
c = 25
print(c/4) # 6.25以上就是整理的 每日leetcode 系列的开篇.
其中每种解法后面的时间复杂度, 空间复杂度分析可能不太准确,仅供参考.
另外对本题有 不同的见解 or 不理解的地方可以一起交流~
边栏推荐
- SQL Server - Window Function - 解决连续N条记录过滤问题
- Making single test so simple -- initial experience of Spock framework
- 429-二叉树(108. 将有序数组转换为二叉搜索树、538. 把二叉搜索树转换为累加树、 106.从中序与后序遍历序列构造二叉树、235. 二叉搜索树的最近公共祖先)
- labelimg使用指南
- Market status and development prospect forecast of global handheld ventilator industry in 2022
- 中金证券经理给的开户二维码安全吗?找谁可以开户啊?
- shell脚本常用命令(四)
- Is it safe to buy stocks online and open an account?
- Erreur Keil de Huada Single Chip Computer La solution de Weak
- 买股票在券商经理的开户链接上开户安全吗?求大神赐教
猜你喜欢

GIS remote sensing R language learning see here

binder hwbinder vndbinder

什么是SSR/SSG/ISR?如何在AWS上托管它们?

Don't worry. This is the truth about wages in all industries in China

GIS遥感R语言学习看这里

Bit. Store: long bear market, stable stacking products may become the main theme

VS code 运行yarn run dev 报yarn : 无法加载文件XXX的问题

International School of Digital Economics, South China Institute of technology 𞓜 unified Bert for few shot natural language understanding

海底电缆探测技术总结

華大單片機KEIL報錯_WEAK的解决方案
随机推荐
Bit.Store:熊市漫漫,稳定Staking产品或成主旋律
Vs code runs "yarn run dev" and reports "yarn": the file XXX cannot be loaded
华大单片机KEIL添加ST-LINK解决方法
经纬度分析
金鱼哥RHCA回忆录:DO447管理项目和开展作业--创建作业模板并启动作业
The Fifth Discipline: the art and practice of learning organization
数仓的字符截取三胞胎:substrb、substr、substring
Current market situation and development prospect forecast of the global ductless heating, ventilation and air conditioning system industry in 2022
作为软件工程师,给年轻时的自己的建议(下)
Don't worry. This is the truth about wages in all industries in China
Character interception triplets of data warehouse: substrb, substr, substring
DCC888 :Register Allocation
【云驻共创】高校数字化差旅建设“解决之道”
工作流自动化 低代码是关键
Labelimg usage guide
使用logrotate对宝塔的网站日志进行自动切割
1030 Travel Plan
Mathematical derivation from perceptron to feedforward neural network
Error reported by Huada MCU Keil_ Weak's solution
信息学奥赛一本通 1333:【例2-2】Blah数集 | OpenJudge NOI 3.4 2729:Blah数集