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

    运行结果:

  • 相关阅读:
    课程总结1
    网站概要设计说明书
    数据库设计说明书
    团队项目之7天工作计划
    NABC
    敏捷开发综述
    二维数组最大子数组
    电梯调度
    输出整数数组中 最大的子数组的结果
    【自习任我行】第二阶段个人总结10
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4096700.html
Copyright © 2011-2022 走看看