[leetcode.com]算法题目 - Plus One

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

 

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int> &digits) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         bool allNine = true;    
 7         int size = digits.size();
 8         
 9         for(int i = 0; i< size; i++){
10             if(digits[i] != 9){
11                 allNine = false;
12                 break;
13             }
14         }
15         
16         if(allNine){
17             vector<int> result(1+size, 0);
18             result[0] = 1;
19             return result;
20         }
21         
22         vector<int> result(size);
23         
24         for(int i=0;i<size;i++){
25             result[i]=digits[i];
26         }
27         
28         result[size-1] += 1;
29         int k = size-1;
30         
31         while(10==result[k]){
32             result[k] = 0;
33             k--;
34             result[k]++;
35         }
36         
37         return result;
38     }
39 };
我的答案

思路:可能出现的意外情况只有数字全是9的时候,这种情况单独拿出来讨论一下,剩下的情况都不可能全为9了。

posted on 2013-09-11 22:18  Horstxu  阅读(241)  评论(0编辑  收藏  举报

导航