Skip to content

Instantly share code, notes, and snippets.

@jsphkhan
Created June 27, 2018 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsphkhan/e8244b2c2187db5e702a2328b974f1f2 to your computer and use it in GitHub Desktop.
Save jsphkhan/e8244b2c2187db5e702a2328b974f1f2 to your computer and use it in GitHub Desktop.
Given an array of numbers, add one to it. Take care of carry overs
/*
[1,2,3,4] => [1,2,3,5]
[1,2,9] => [1,3,0]
[1,2,9,9] => [1,3,0,0]
[9,9,9] => [1,0,0,0]
*/
function addOne(arr) {
let sum = 0, carry = 1;
for(let i = (arr.length - 1); i >= 0; i--) {
sum = arr[i] + carry;
arr[i] = sum%10;
if(sum === 10) {
carry = 1;
} else {
carry = 0;
}
}
//at the end of the loop if carry is one
if(carry === 1) {
arr.unshift(carry); //for cases like [9,9,9]
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment