LeetCode66 Plus One

题目:

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

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

分析:

基本的加法操作,用carry处理进位即可,注意最后多一位的时候insert一个1。

代码:

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digits) {
 4         int carry = 0;
 5         digits[digits.size() - 1]++;
 6         for (int i = digits.size() - 1; i >= 0; --i) {
 7             int temp = digits[i] + carry;
 8             if (temp == 10) {
 9                 carry = 1;
10                 temp = 0;
11             }
12             else {
13                 carry = 0;
14             }
15             digits[i] = temp;
16         }
17         if (carry == 1) {
18             digits.insert(digits.begin(), 1);
19         }
20         return digits;
21     }
22 };

 

posted @ 2016-09-21 22:53  wangxiaobao1114  阅读(184)  评论(0编辑  收藏  举报