Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 리트코드
- 쉬움
- math
- 중간
- linked list
- 재귀
- 문자열
- 이진트리
- dfs
- matrix
- tree
- backtracking
- two pointers
- hash table
- easy
- DP
- Depth-first Search
- recursive
- Python
- string
- leetcode
- Medium
- sorting
- binary search
- Array
- 미디움
- Binary
- HashTable
- list
- binary tree
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 66(Plus One, Python) 본문
1. 문제 링크
Plus One - LeetCode
Can you solve this real interview question? Plus One - You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-
leetcode.com
2. 문제 설명
- 리스트 [1, 2, 3]가 주어지면 123에 1을 더한 124를 리스트로 바꾸어 [1, 2, 4]를 반환
3. 처음 풀이
- 주어진 리스트의 원소를 순서대로 꺼내면서 10배씩 하여 더해주면 [1, 2, 3]을 통해 123을 얻는다
- 여기에 1을 더하여 124를 얻은 후
- 124를 10으로 나눈 몫과 나머지 중 나머지를 result 리스트 제일 앞에 넣고, 그 몫을 다시 10으로 나눈 나머지를 result 리스트 제일 앞에 넣는 것을 반복하면 [1, 2, 4]가 얻어짐
- list.insert(index,val) 하면 list의 index 위치에 val을 넣는다.
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
a=0
result=[]
for i in digits: #예시: [1,2,3]을 123으로 바꾸어 a에 저장
a=10*a+i #10*0+1=1 → 10*1+2=12 → 10*12+3=123
a+=1 #더하기 1 해주기 → 124
while a>=10: #예시: 124를 [1,2,4]로 바꾸기
result.insert(0, a%10) #result 0번째 위치에 124를 10으로 나눈 나머지 4를 넣고
a=a//10 #124를 10으로 나눈 몫 12로 a 업데이트 → 그 다음엔 2를 result 0번째에 넣고 a=1로 업데이트
result.insert(0, a) #마지막 a=1을 result 0번째 위치에 넣기
return result
4. 다른 풀이
- [1, 2, 3]이 주어졌다고 하자.
- list의 각 문자열을 더하여 하나의 문자열로 더하여 '123'을 만든 후 int() 이용하여 int 123으로 바꾼다.
- 이 값에 1을 더한 후 str()로 문자열 '124'로 바꾼 후 list()에 넣어 리스트 ['1', '2', '4']로 바꾼다.
- 리스트의 각 원소에 int()를 적용한 후 다시 list로 바꾸어 주면 [1, 2, 4]가 된다. 이 과정은 map함수를 이용하면 간단
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
s = ""
for i in digits:
s = s+str(i)
no = int(s)+1
gg = list(str(no))
return list(map(int, gg))
5. 배운점
- list.insert(index,val) 하면 list의 index 위치에 val을 넣는다.
- map 함수를 쓰는 꼴
- list(map(함수, 리스트))
- tuple(map(함수, 튜플))
- 함수에는 괄호를 안 넣는다. 파라미터로 전달된 함수를 리스트나 튜플의 각 대상에 적용한 후 그 결과값을 다시 모아 리스트나 튜플로 반환함
- list() 함수는 str을 한 글자씩 list로 바꾸어 주며 int는 넣으면 오류가 난다.
list(’abc’) #[’a’,’b’,’c’]
list(123) #에러
list(’123’) #[’1’,’2’,’3’]
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 69(Sqrt(x), Python) (0) | 2023.11.10 |
---|---|
LeetCode 67(Add Binary, Python) (0) | 2023.11.09 |
LeetCode 58(Length of Last Word, Python) (0) | 2023.11.07 |
LeetCode 35(Search Insert Position, Python) (0) | 2023.11.06 |
LeetCode 26(Remove Duplicates from Sorted Array, Python) (0) | 2023.11.05 |