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


    思路:先将list翻转。再在list尾部加一个0。假设第一个数非9,则直接将其加1;否则遍历list。将遇到的第一个非9的数加1。其前面的数都置零。假设list的最后一个数为0,则将其删除。

    最后将list再翻转一次即得到结果。


    代码:

    vector<int> Solution::plusOne(vector<int> &digits)
    {
        reverse(digits.begin(),digits.end());
        digits.push_back(0);
        int length = digits.size();
        bool flag = false;
        for(int i = 0;i < length;i++)
        {
            if(digits[i] == 9)
            {
                flag = true;
                continue;
            }
            else
            {
                if(flag)
                {
                    for(int j = 0;j < i;j++)
                        digits[j] = 0;
                    digits[i]++;
                    break;
                }
                else
                {
                    digits[i]++;
                    break;
                }
    
            }
        }
        if(digits[length-1] == 0)
            digits.pop_back();
        reverse(digits.begin(),digits.end());
        return digits;
    }
    


  • 相关阅读:
    学习Tomcat(三)
    TIME_WAIT 优化注意事项
    TIME_WAIT 优化
    TCP(一)
    TCP(二)
    TCP(三)
    5-14 练习题及答案
    5-14 进程池
    5-11 操作系统介绍
    5-8套接字socket
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/7112707.html
Copyright © 2011-2022 走看看