[Leetcode] Plus One

Plus One 题解

题目来源:https://leetcode.com/problems/plus-one/description/


Description

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.

Solution

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int size = digits.size();
        for (int i = size - 1; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        vector<int> res(size + 1, 0);
        res[0] = 1;
        return res;
    }
};


解题描述

这道题题意是,给出一个数组代表一个十进制数,高位排在前面,求将这个数加1后的结果同样的数组表示。

这里关键就是关于进位的问题,而进位只有在数位是9的时候才会发生,因此只需要从低位向高位扫描

  • 出现小于9的数字直接自增数位,返回原数组
  • 否则则将数位置为0继续扫描。
  • 如果扫描完毕没有返回,说明最高位需要补上1,则新建一个数组,最高位设为1,低位全为0即可。
posted @ 2018-02-03 13:32  言何午  阅读(123)  评论(0编辑  收藏  举报