美文网首页
66. Plus One

66. Plus One

作者: i_Eloise | 来源:发表于2018-01-23 09:37 被阅读0次

    Question
    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

    You may assume the integer do not contain any leading zero, except the number 0 itself.

    The digits are stored such that the most significant digit is at the head of the list.

    • first attempt
      这不是一个好的答案
      因为我没有考虑到vector的长度 如果它很长,就算使用long long也是无法储存sum的,而且还使用了2次循环
    class Solution {
    public:
        vector<int> plusOne(vector<int>& digits) {
            long long sum=0;
            for(unsigned i =0;i <digits.size();i++)
                sum=sum*10+digits[i];
            sum = sum+1;
            vector<int> ve;
            if(sum==0)
                return ve;
    
            while(sum!=0)
            {
                ve.insert(ve.begin(),sum%10);
                sum=sum/10;
            }
            while(ve.size()!=0&&ve.front()==0)
                ve.erase(ve.begin());
    
            return ve;
        }
    };
    
    • improved
      改进后
    class Solution {
    public:
        vector<int> plusOne(vector<int>& digits) {
        vector<int>::reverse_iterator it;
            int carry=1;
            for(it = digits.rbegin();it!=digits.rend();it++)
            {
                if(carry==1)
                {
                    if( ((*it)+carry)==10 )
                    {
                        (*it)= 0;
                        carry=1;
    
                    }
                    else
                    {
                        (*it)=(*it)+carry;
                        carry = 0;
                    }
                }
                else
                    break;
            }
            if(carry ==1)
                digits.insert(digits.begin(),1);
            return digits;         
        }
    };
    

    相关文章

      网友评论

          本文标题:66. Plus One

          本文链接:https://www.haomeiwen.com/subject/buijaxtx.html