No.66 Plus One

No.66 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的功能

注意:从后向前加,注意边界和进位即可。

细节!

 1 #include "stdafx.h"
 2 #include <map>
 3 #include <vector>
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class Solution
 8 {
 9 public:
10     vector<int> plusOne(vector<int> &digits)
11     {//给定一个数组表示的非负数,实现该数加1
12         int carry = 0;//保存进位
13         int size = digits.size();
14         vector<int> res;
15         if(size == 0)
16         { 
17             res.push_back(1);
18             return res;
19         }
20         res = digits;
21         for(int i=size-1; i>=0 ; i--)//从后向前加
22         {
23             if(i == size-1)
24             {
25                 res[i] = (digits[i]+1)%10;
26                 carry = (digits[i]+1)/10;
27             }
28             if(carry == 0)
29                 break;
30             else
31             {
32                 res[i] = (digits[i]+carry)%10;
33                 carry = (digits[i]+carry)/10;
34             }
35         }
36         if(carry!=0)
37             res.insert(res.begin(),carry);
38         
39         return res;
40     }
41 };
42 
43 int main()
44 {
45     Solution sol;
46     int data[] = {9,9,8,4,2};
47     vector<int> test(data,data+sizeof(data)/sizeof(int));
48     vector<int> res;
49     for(const auto &i : test)
50         cout << i << " ";
51     cout << endl;
52     res = sol.plusOne(test);
53     for(const auto &i : res)
54         cout << i << " ";
55     cout << endl;    
56 }

 

 

posted @ 2015-06-11 21:27  人生不酱油  阅读(141)  评论(0编辑  收藏  举报