zoukankan      html  css  js  c++  java
  • 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.

    题目:

    给定一个十进制数,用数组表示每一位,要求返回加一后的结果

    思路:

    从数组尾部到头部处理,需要判断是否最后要进位,如果要进位需要在vector的最前面插入1.

    C++代码如下:

    #include<iostream>
    #include<vector>
    using namespace std;
    
    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            int size=digits.size()-1;
            while(size>=0)
            {
                if(digits[size]<9)
                {
                    digits[size]+=1;
                    break;
                }
                else
                {
                    digits[size]=0;
                    size--;
                }
            }
            size++;
            if(size==0&&digits[size]==0)
            {
                digits.insert(digits.begin(),1);
            }
            return digits;
        }
        void Convert(int num,vector<int> &digits)
        {
            if(num>=10)
                Convert(num/10,digits);
            digits.push_back(num%10);
        }
    };
    
    int main()
    {
        vector<int> digits;
        int num;
        cin>>num;
        Solution s;
        s.Convert(num,digits);
        for(auto v:digits)
            cout<<v<<" ";
        cout<<endl;
        s.plusOne(digits);
        for(auto v:digits)
            cout<<v<<" ";
        cout<<endl;
    }

    运行结果:

  • 相关阅读:
    dubbox编译
    fastdfs的启动停止
    fastDFS单机
    Dsu on tree算法
    The 2017 ACM-ICPC Asia Beijing Regional Contest(重现赛)
    2019南京ICPC(重现赛) F
    Codeforces Round #634 (Div. 3)
    Codeforces Round #632 (Div. 2)
    HDU 6521 Party(线段树)
    牛客小白月赛20
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4096700.html
Copyright © 2011-2022 走看看