Skip to content

Instantly share code, notes, and snippets.

@ryanseys
Last active August 29, 2015 14:03
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 ryanseys/20ccd40c448cca275039 to your computer and use it in GitHub Desktop.
Save ryanseys/20ccd40c448cca275039 to your computer and use it in GitHub Desktop.
Increment number represented in Array
/**
* 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