GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode-javascript/66. 加一.md at main · lxhguard/leetcode-javascript

Expand file tree

/

66. 加一.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
52 lines (40 loc) · 1.37 KB
/

66. 加一.md

Copy path

File metadata and controls

52 lines (40 loc) · 1.37 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

题目描述

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

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

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

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

题解一:API 先String再Array

解题思路:将参数数组转为String,再加一,最后转为Array。注意,如果整数大小超过最大安全整数,则使用BigInt。

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    let big = BigInt(digits.join('')) + 1n;
    let arr = String(big).split('');
    return arr;
};

题解二:

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function (digits) {
    var carry = 1; // 我们将初始的 +1 也当做是一个在个位的 carry
    for (var i = digits.length - 1; i > -1; i--) {
        if (carry) {
            var sum = carry + digits[i];
            digits[i] = sum % 10;
            carry = sum > 9 ? 1 : 0; // 每次计算都会更新下一步需要用到的 carry
        }
    }
    if (carry === 1) {
        digits.unshift(1); // 如果carry最后停留在1,说明有需要额外的一个长度 所以我们就在首位增添一个 1
    }
    return digits;
};
You are visitor 01402877 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.