Skip to content

Instantly share code, notes, and snippets.

@nuweb
Last active December 14, 2015 18:39
Show Gist options
  • Save nuweb/5131147 to your computer and use it in GitHub Desktop.
Save nuweb/5131147 to your computer and use it in GitHub Desktop.
A CodePen by nuweb. Increment large numbers in JavaScript
// increment/decrement large integers in JavaScript
var num = "900719925474599945678999";
function incdecLargeInt(str, operation){
var arr = str.split("");
var lastInt = Number(arr.pop());
if(lastInt===9){
// implement carry over
fixCarryOver(num.split(''));
var zx = res.reverse().join('');
// edge case when all are '9's
if(Number(zx)===0) {
zx = "1" + zx;
}
console.log(zx);
} else {
lastInt++;
console.log(arr.join('') + lastInt.toString());
}
}
var res = [], CARRY = true;
function fixCarryOver(arr){
if(arr.length){
var tstr = arr.pop();
if(tstr==="9" && CARRY) {
res.push("0");
CARRY = true;
} else {
if(CARRY) {
tstr = Number(tstr);
tstr++;
}
res.push(tstr.toString());
CARRY = false;
}
} else {
return res;
}
fixCarryOver(arr);
}
incdecLargeInt(num, "inc");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment