[코딩연습] LeetCode - Plus One
문제 📄
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1 🔎
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2 🔎
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Example 3🔎
Input: digits = [0]
Output: [1]
Constraints 📢
- 1 <= digits.length <= 100
- 0 <= digits[i] <= 9
코드 👩🏻💻
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int len = digits.size();
int i = len-1;
int end = digits[i] + 1;
if (end == 10) {
int carry = 1;
while(carry) {
if (i == 0) {
digits.insert(digits.begin(), 0);
i++;
}
digits[i-1] ++;
digits[i] = 0;
if (digits[i-1] == 10)
i --;
else
carry = 0;
}
}
else
digits[i] = end;
return digits;
}
};
결과 ✨
LeetCode는 test case로 코드를 run한 후에 submit을 하면 위와 같이 코드가 성공적으로 돌아가는지 보여준다. 여러 번의 시도로 에러를 고치려고 노력해 봤지만 잘 되지 않아서 다른 분들의 코드를 참고해서 마지막인 7번의 시도에서 success를 받았다. 언젠가는 다른 코드를 참고하지 않고 내 힘으로 효율적이고 깔끔한 코드를 쓸 수 있도록 열심히 공부해야 겠다 🤓💪🏻
개념 정리 ✏️
C++ 표준 라이브러리(Standard Template Library) Vector class
- 헤더 파일: < vector >
- vector의 원소의 개수를 구하는 함수: size()
- vector의 첫번째 위치를 구하는 함수: begin()
- vector에 원소 추가: insert(index, value)
vector<int> vec = {1, 2, 3, 4, 5}; cout << vec.size(); // 5 vec.insert(vec.begin(), 2); // vector의 맨 앞에 원소 2 삽입
[출처: https://coding-factory.tistory.com/596]
Author And Source
이 문제에 관하여([코딩연습] LeetCode - Plus One), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@bsm4045/코딩연습-LeetCode-Plus-One저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)