码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode之“数组”:Plus One

时间:2015-06-20 11:45:49      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

  题目链接

  题目要求:

  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 };

 

LeetCode之“数组”:Plus One

标签:

原文地址:http://www.cnblogs.com/xiehongfeng100/p/4590353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!