LeetCode每日一题(五):加一

给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

示例 1:

输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:

输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/plus-one

思路:

先检查末尾元素是否等于9,若不等于,则将该位元素直接加1返回数组。

若等于,则倒序遍历数组,检查每个数组元素是否等于9,若等于,将该位置0(9+1=10),继续检查前一位是否为9,不等于则前一位直接+1返回数组,等于则继续检查,直到数组头部元素为9,则向数组头部插入1

代码:

class Solution {

    /**
     * @param Integer[] $digits
     * @return Integer[]
     */
    function plusOne($digits) {
        if($digits[count($digits) - 1] == 9) { // 判断最后一个数组是否为9
            for ($j = count($digits) - 1; $j >= 0; $j--) { // 循环数组直到不是9的数组出现
                if($digits[$j] < 9) {
                    $digits[$j] += 1; // 将此并返回
                    return $digits;
                } elseif($digits[$j] == 9) {
                    $digits[$j] = 0;
                    if($j == 0) { // 如果第一位数字是9, 在数组头位插入 1
                        array_unshift($digits, 1);
                        return $digits;
                    }
                }
            }
        } else {
            $digits[count($digits) - 1] += 1;
        }
        return $digits;
    }
}

执行用时:12 ms,内存消耗:14.6 MB

慢慢来才是最快的
原文地址:https://www.cnblogs.com/jongty/p/11654321.html