LeetCode - Plus One [C++]

somengยท2021๋…„ 8์›” 6์ผ
0

๋ฌธ์ œ ๐Ÿ“„

๐Ÿ“Ž 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]

profile
๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป iOS Developer

0๊ฐœ์˜ ๋Œ“๊ธ€