首页 > 编程语言 > 详细

LeetCode之“数组”:Plus One

时间:2015-06-20 11:43:30      阅读:186      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!