DEV Community

Cover image for Add plus one to the integer
chandra penugonda
chandra penugonda

Posted on

Add plus one to the integer

Good morning! Here's your coding interview problem for today.

This problem was asked by Spotify.

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

Example

function plusOne(digits){

};

console.log(plusOne([1,2,3])); // [1,2,4]
console.log(plusOne([4,3,2,1])); // [4,3,2,2]
Enter fullscreen mode Exit fullscreen mode

Solution

function plusOne(digits) {
  let i = digits.length - 1;
  while (i >= 0 && digits[i] === 9) {
    digits[i] = 0;
    i--;
  }
  if (i === -1) {
    digits.unshift(1);
  } else {
    digits[i] += 1;
  }
  return digits;
}

console.log(plusOne([1, 2, 3])); // [1,2,4]
console.log(plusOne([4, 3, 2, 1])); // [4,3,2,2]

Enter fullscreen mode Exit fullscreen mode

Implementation

  • We start from the rightmost digit and keep adding one until we encounter a digit that is less than 9. This is because if the digit is 9, adding one would result in a carry-over to the next digit.
  • If we encounter a digit less than 9, we simply increment it by one and return the updated array of digits.
  • If we reach the leftmost digit and it was 9, we need to add a new digit at the beginning of the array before incrementing the leftmost digit. This is because adding one to 9 would result in a carry-over to the leftmost digit.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay