【Leetcode】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.

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

模拟。

posted @ 2014-03-19 22:13  小菜刷题史  阅读(188)  评论(0编辑  收藏  举报