[코딩연습] LeetCode - Plus One

문제 📄

📎 LeetCode 문제 링크

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]

좋은 웹페이지 즐겨찾기