Daily question of JS algorithm question – 6. Plus one

Time:2020-3-12

Daily question of JS algorithm question - 6. Plus one

The official account of WeChat:Drunk front endFollow for more topics.

Title

Q: Given a nonnegative integer represented by a nonempty array of integers, add one to the number. The highest digit is stored at the top of the array. Each element of the array only stores a single digit. You can assume that the integer will not start with zero except the integer 0.

Input: [1,2,3] output: [1,2,4]

  • Example 2:

Input: [4,3,2,1] output: [4,3,2,2]

  • Example 3:

Input: [3,2,9] output: [3,3,0]

  • Example 4:

Input: [9,9,9] output: [1,0,0,0]

Answer

const plusOne = nums => {
    const len = nums.length;
    for(let i = len -1; i >= 0; i--) {
      nums[i]++;
      nums[i]%=10;
      if(nums[i] !== 0){
        return nums;
      }
    }
    nums.unshift(1);
    return nums;
}

Update a algorithm problem everyday, add a concern, old fellow iron!
Daily question of JS algorithm question - 6. Plus one