66 - Plus One

来源:互联网 发布:手机钉钉 请检查网络 编辑:程序博客网 时间:2024/06/06 00:02

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.

Subscribe to see which companies asked this question

思路解析:

本题不难理解。在题意上纠结了五分钟。其实就是一个数字,其中的每一位是数组中的每一个元素。

class Solution {public:    vector<int> plusOne(vector<int>& digits)     {        if (digits[digits.size() - 1] != 9)        {            digits[digits.size() - 1] ++;            return digits;        }        else        {            digits[digits.size() - 1] = 0;            int carry = 1;                        for (int i = digits.size() - 2; i >=0; i--)            {                if (digits[i] != 9)                {                    digits[i]++;                    return digits;                }                else                {                    digits[i] = 0;                }            }                        //都是9的情况            vector<int> res(digits.size() + 1, 0);            res[0] = 1;            return res;        }    }};



0 0
原创粉丝点击