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         vector<int> ret;
 5         int sz = digits.size();
 6         if(sz == 0)
 7             return ret;
 8         
 9         int carry = 1;
10         for(int i = sz - 1; i > -1; i--)
11         {
12             if(carry + digits[i] == 10)
13                 ret.insert(ret.begin(), 0);
14             else
15             {
16                 ret.insert(ret.begin(), carry + digits[i]);
17                 carry = 0;
18             }
19         }
20         
21         if(carry == 1)
22             ret.insert(ret.begin(), 1);
23             
24         return ret;
25     }
26 };

 

posted @ 2015-06-20 11:15  峰子_仰望阳光  阅读(181)  评论(0编辑  收藏  举报