Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

66:加一 #2

Open
funnycoderstar opened this issue Aug 19, 2018 · 0 comments
Open

66:加一 #2

funnycoderstar opened this issue Aug 19, 2018 · 0 comments

Comments

@funnycoderstar
Copy link
Owner

JavaScript实现LeetCode第66题:加一

题目描述

给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。

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

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

示例 1:

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

示例 2:

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

思路

我们需要给这个数字加一,即在末尾数数字加一, 如果是9,则存在进位问题, 如果前面的位数是9,则需要继续向前进位
具体算法:
1.判断最后一位是否为小于9, 如果是,则加一返回;如果是9,则该位置赋值为0,再继续查找前一位, 直到查到第一位, 若第一位原本是9,加一会产生新的一位
2.查找运算完的第一位是否为0, 如果是 ,则在最前头一位加一个1

方法

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    const length = digits.length;
    for(let i = length -1; i >=0; --i) {
        if(digits[i] < 9) {
            ++digits[i];
            return digits;
        }
        digits[i] = 0;
    }
    let res = [1];
    return res.concat(digits);
};
@funnycoderstar funnycoderstar changed the title JavaScript实现LeetCode第66题:加一 66:加一 Aug 24, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant