Skip to content

66. 加一

66. 加一

代码

javascript
// 66. 加一:https://leetcode.cn/problems/plus-one/description/
// 输入:digits = [1,2,3]
// 输出:[1,2,4]

export function plusOne (digits) {
  let add = 1
  let ad = 0
  for (let idx = digits.length - 1; idx >= 0; idx--) {
    const cur = digits[idx] + add + ad
    add = 0
    if (cur > 9) {
      digits[idx] = cur % 10
      ad = 1
    } else {
      digits[idx] = cur
      ad = 0
    }
  }
  if (ad > 0) {
    digits = [ad, ...digits]
  }
  return digits
}
typescript
// 66. 加一:https://leetcode.cn/problems/plus-one/description/
// 输入:digits = [1,2,3]
// 输出:[1,2,4]

export function plusOne (digits: number[]): number[] {
  let add = 1
  let ad = 0
  for (let idx = digits.length - 1; idx >= 0; idx--) {
    const cur = digits[idx] + add + ad
    add = 0
    if (cur > 9) {
      digits[idx] = cur % 10
      ad = 1
    } else {
      digits[idx] = cur
      ad = 0
    }
  }
  if (ad > 0) {
    digits = [ad, ...digits]
  }
  return digits
}

测试代码

ts
import { expect, test } from 'vitest'
import { plusOne } from './typescript.ts'
import { plusOne as plusOneJs } from './javascript.js'

test(`plusOne`, () => {
  expect(plusOne([1,2,3])).toEqual([1,2,4])
  expect(plusOne([1,2,9])).toEqual([1,3,0])
  expect(plusOne([9])).toEqual([1,0])
})

test(`plusOneJs`, () => {
  expect(plusOneJs([1,2,3])).toEqual([1,2,4])
  expect(plusOneJs([1,2,9])).toEqual([1,3,0])
  expect(plusOneJs([9])).toEqual([1,0])
})