Plus One

我觉得逻辑上是清晰的,但是写起来很别扭,感觉不好写,写出来,结果是错的······

而且vector,哪里是头哪里是尾?

1 2 3 4 5

我的想法是1是尾,5是头,每次添加都是从尾添加的。而且这个表示的数应该是12345而不是54321,不知道这么理解对不?

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int> &digits) {
 4         vector<int>::size_type i,n;
 5         n=digits.size();
 6         for(i=0;i<n;++i)
 7         {
 8             if(digits[i]!=9)
 9             {
10                 digits[i]++;
11                 //return;  //Submission Result: Compile Error 
12                 //Line 11: return-statement with no value, in function returning 'std::vector<int>' [-fpermissive]
13                 break;
14             }
15             else
16             {
17                 if(i!=(n-1))
18                 {
19                     digits[i]=0;//放心地置0吧,进位在第10行表现的
20                 }
21                 else
22                 {
23                     digits[i]=0;
24                     //digits.push_back(1);
25                     //Input:[9]  Output:[0,1]   Expected:[1,0]
26                     //这个说明我应该是把头和尾理解反了
27                 }
28             }
29         }
30         return digits; //这个别忘记写了
31     }
32 };

题目上说:The digits are stored such that the most significant digit is at the head of the list.

意思应该是说表头最大,我列的表格表示的是12345应该没错,不过1是头,5是尾

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int> &digits) {
 4         //vector<int>::size_type i,n; 这个是看着《C++ primer》写的
 5         int i,n;
 6         n=digits.size();
 7         for(i=(n-1);i>=0;--i)
 8         {
 9             if(digits[i]!=9)
10             {
11                 digits[i]++;
12                 //return;  //Submission Result: Compile Error 
13                 //Line 11: return-statement with no value, in function returning 'std::vector<int>' [-fpermissive]
14                 break;
15             }
16             else
17             {
18                 if(i!=0)
19                 {
20                     digits[i]=0;//放心地置0吧,进位在第10行表现的
21                 }
22                 else
23                 {
24                     digits[i]=1;
25                     digits.push_back(0);
26                 }
27             }
28         }
29         return digits; //这个别忘记写了
30     }
31 };

AC

原文地址:https://www.cnblogs.com/crane-practice/p/3585178.html