当前位置:网站首页>Leetcode 989. Integer addition in array form (simple)
Leetcode 989. Integer addition in array form (simple)
2022-06-27 20:37:00 【I am fat tiger】
Leetcode 989. The addition of integers in the form of arrays ( Simple )
Topic link
https://leetcode-cn.com/problems/add-to-array-form-of-integer/
Train of thought explanation
The official sample : Input :A = [1,2,0,0], K = 34 Output :[1,2,3,4] explain :1200 + 34 = 1234
From the beginning, I began to think according to the ideas in the topic examples , Then write the understanding method 1
Solution 1 :
1. take Numeric array -> String array
2. Concatenate the strings in the array , use eval Function to fetch a number from a string and k Sum up , Then it is converted to a string
3. The string -> Numeric array
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]
Complexity analysis
- Time complexity : O(N)
- Spatial complexity : O(N)
python Knowledge about
- keyword eval Used to extract expressions from strings , Then return the value of the expression . Example :
print(eval("[1, 2, 3]")) # [1, 2, 3]
print(eval("pow(2, 3)")) # 8
among pow(2, 3) It means to calculate 2 Of 3 Power , The result is 8
- List derivation
print([i for i in range(5)]) # [0, 1, 2, 3, 4]
This is equivalent to :
arr = []
for i in range(5):
arr.append(i)
print(arr)
- Array -> character string (join Usage of )
a = ['1', '2', '3', '4']
print("".join(a)) # 1234The above solution 1 is actually a trick , The normal practice should be to use The idea of binary To do , For example, solution 2 . This solution is seen from the problem solution , According to the thought of the boss
Solution 2
Topic ideas
The idea of this question can be compared with 2 A vertical calculation of the addition of numbers ( full 10 Into the 1), The algorithmic idea used is two finger needling !
1. Definition 2 A pointer to the , Point to respectively num and k At the end of
2. Go back and forth , As long as the longest string has a value, it will be traversed . During traversal , If shorter character string or list No corresponding index , Then use numerical value 0 Instead of
3. Finally, judge carry Variable , If carry > 0, Delegates need to be manually added once 1( Because maybe in the last judgment above ,carry>0, Then the loop ends )
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 # Whether to need a carry in identifier
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]
Complexity analysis
- Time complexity : O(N)
- Spatial complexity : O(1)
python Knowledge about
- Flip the list
a = [1, 2, 3, 4]
The way 1:
print(a[::-1]) # The flipping method used in this question
The way 2:
a.reverse() # Pay attention to reverse, What is changed is the order of the elements in the original array !
print(a)
The way 3:
print(list(reversed(a))) # ['4', '3', '2', '1']
# Be careful reversed The result is a iterator object , Need to use list() Function to list
print(a) # ['1', '2', '3', '4'] # Use reversed Will not affect the original list
- Remainder + Get divisor
# Take the remainder
a = 12
print(a % 10) # 2
Knowledge point :
// Represents integer division
/ Express Floating point division , Return floating point result
# Get divisor ( Integers ): //
b = 25
print(25//4) # 6
# Get divisor ( Floating point numbers ): /
c = 25
print(c/4) # 6.25That's what it's all about everyday leetcode The beginning of the series .
After each of these solutions Time complexity , Spatial complexity The analysis may not be accurate , For reference only .
In addition, I have Different opinions or What I don't understand You can talk to each other ~
边栏推荐
- CSDN skill tree experience and product analysis (1)
- Redis持久化
- MongoDB简介及典型应用场景
- 如何降低用户关注的非必要页面的权重传递?
- #夏日挑战赛# OpenHarmony HiSysEvent打点调用实践(L2)
- Massive data attended the Lanzhou opengauss meetup (ECOLOGICAL NATIONAL trip) activity, enabling users to upgrade their applications with enterprise level databases
- 探秘GaussDB,听听客户和伙伴怎么说
- Rust advanced ownership - memory management
- [help] troubleshooting of JVM's high CPU resource consumption
- redis数据结构
猜你喜欢

A distribution fission activity is more than just a circle of friends

Ble Bluetooth module nrf518/nrf281/nrf528/nrf284 chip scheme comparison

Practice of combining rook CEPH and rainbow, a cloud native storage solution

It took me 6 months to complete the excellent graduation project of undergraduate course. What have I done?

SQL audit platform permission module introduction and account creation tutorial

redis数据结构

CSDN 技能树使用体验与产品分析(1)

【精品必读】Linux系统Oracle数据库趣解子查询

database engine

Accumulating power in the middle stage, UFIDA IUAP builds a new base for digital intelligence of social enterprises
随机推荐
回溯相关问题
Manage rust project through cargo
【STL编程】【竞赛常用】【part 3】
Postman Chinese tutorial (postman Chinese version)
NVIDIA three piece environment configuration
Crontab's learning essays
SQL报了一个不常见的错误,让新来的实习生懵了
云原生存储解决方案Rook-Ceph与Rainbond结合的实践
Database optimization
Openharmony hisysevent dotting and calling practice of # Summer Challenge (L2)
实现字符串MyString
Cloud native Security Guide: learn kubernetes attack and defense from scratch
openssl客户端编程:一个不起眼的函数导致的SSL会话失败问题
What is a low code development platform? Why is it so hot now?
Web APls 阶段——第十四节——本地存储
[array]bm99 clockwise rotation matrix - simple
Accumulating power in the middle stage, UFIDA IUAP builds a new base for digital intelligence of social enterprises
最佳实践:优化Postgres查询性能(下)
CSDN 技能树使用体验与产品分析(1)
Bit.Store:熊市漫漫,稳定Staking产品或成主旋律