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. Plus One #247

Open
Tcdian opened this issue Jul 6, 2020 · 1 comment
Open

66. Plus One #247

Tcdian opened this issue Jul 6, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jul 6, 2020

66. Plus One

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

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

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

Example 1

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
@Tcdian
Copy link
Owner Author

Tcdian commented Jul 6, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    let carry = 1;
    const result = new Array(digits.length);
    for (let i = digits.length - 1; i >= 0; i--) {
        result[i] = (digits[i] + carry) % 10;
        carry = Math.floor((digits[i] + carry) / 10);
    }
    if (carry) {
        result.unshift(carry);
    }
    return result;
};
  • TypeScript Solution
function plusOne(digits: number[]): number[] {
    let carry = 1;
    const result: number[] = new Array(digits.length);
    for (let i = digits.length - 1; i >= 0; i--) {
        result[i] = (digits[i] + carry) % 10;
        carry = Math.floor((digits[i] + carry) / 10);
    }
    if (carry) {
        result.unshift(carry);
    }
    return result;
};

@Tcdian Tcdian added the Array label Jul 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant