Created
June 27, 2018 18:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
[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