欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LeetCode - 66. Plus One(0ms)

程序员文章站 2022-04-06 13:04:12
Given a non-empty array of digits representing a non-negative integer, plus one to the integer. The digits are stored such that the most significant d ......

Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digits) {
 4         int s = digits.size();
 5         int flag = 0;
 6         if(digits[0] == 9) {
 7             if(digits[s - 1] == 9) {
 8                 for(int i = 1; i < s - 2; i++) {
 9                     if(digits[i] == 9) {
10                         continue;
11                     }
12                     else {
13                         flag = 1;
14                         break;
15                     }
16                 }
17                 if(flag == 0) {
18                     vector<int> res(s + 1);
19                     res[0] = 1;
20                     for(int i = 1; i < s; i++)
21                         res[i] = 0;
22                     return res;
23                 }
24             }
25         }
26         if(digits[s - 1] == 9) {
27             vector<int> res(s);
28             res[s - 1] = 0;
29             int car = 1;
30             for(int i = s - 2; i >= 0; i--) {
31                 res[i] = digits[i] + car;
32                 if(car == 1) {
33                     if(res[i] == 10)
34                         res[i] = 0;
35                     else
36                         car = 0;
37                 }
38             }
39             return res;
40         }
41         else {
42             vector<int> res(digits);
43             res[s - 1] = digits[s - 1] + 1;
44             return res;
45         }
46     }
47 };