LeetCode 66. Plus One

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

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

The digits are stored such that the most significant digit is at the head of the list.


 
Seen this question in a real interview before?  
Yes
No
 
 
这道题要求vector中表示一个整数的各个位数,末尾 + 1,要求返回计算之后的结果, 思路很直接,不难,需要注意的是讨论进位的情况,代码如下:
 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digits) {
 4         int carry = 1;
 5         int len = digits.size();
 6         for (int i = len-1; i >=0 ;i--)
 7         {
 8             digits[i] += carry;
 9             if (digits[i] == 10)
10             {
11                  digits[i] = 0;
12                  carry = 1;
13             }
14             else
15             {
16                 //carry = 0;
17                 return digits;
18             }
19         }
20         digits.insert(digits.begin(),1);
21         return digits;
22     }
23 };

 

posted @ 2018-01-04 15:25  皇家大鹏鹏  阅读(139)  评论(0编辑  收藏  举报