首页 > 其他 > 详细

Leetcode Plus One

时间:2014-10-19 19:45:28      阅读:238      评论: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.

//digits={9,9,9,9},那么经过函数运算变为{1,0,0,0},也就是把vector中各位存储的数字看成一个整数的各个位,digits[0]为最高位

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
       
       if(digits.size() == 0){
           digits.push_back(1);
           return digits;
       } 
       
       int carry = 0;
       int i = 0;
       int current;
       int size = digits.size();
       for(i = size - 1; i >=0 ; i--){
           if(i == size -1){
               current = (digits[i] + 1); 
           } else {
               current = (digits[i] + carry);
           }
           
           carry = current / 10;
           digits[i] = current % 10;
       }
       if(carry != 0){
           digits.insert(digits.begin(), carry);
       }
       return digits;
       
    }
};


Leetcode Plus One

原文:http://www.cnblogs.com/bhlsheji/p/4035250.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!