Last active
August 29, 2015 14:03
-
-
Save ryanseys/20ccd40c448cca275039 to your computer and use it in GitHub Desktop.
Increment number represented in Array
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
/** | |
* Increment number represented in array | |
* | |
* E.g. Take [1, 2, 3] increment to [1, 2, 4] | |
* @param {[Number]} arr Array to increment | |
* @return {[Number]} Array of numbers | |
*/ | |
function increment(arr) { | |
for(var i = arr.length - 1; i >= 0; i--) { | |
if(arr[i] === 9) { | |
arr[i] = 0; | |
if(i === 0) { | |
arr.unshift(1); | |
} | |
} | |
else { | |
arr[i] = arr[i] + 1; | |
break; | |
} | |
} | |
return arr; | |
} | |
console.log(increment([1, 2, 3, 4])); | |
console.log(increment([1, 2, 3, 9])); | |
console.log(increment([9, 9, 9])); | |
console.log(increment([0])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment