Skip to content

Instantly share code, notes, and snippets.

@Songhun
Created October 12, 2011 13:59
Show Gist options
  • Select an option

  • Save Songhun/1281291 to your computer and use it in GitHub Desktop.

Select an option

Save Songhun/1281291 to your computer and use it in GitHub Desktop.
[Javascript] Plus one with string number over integer size
/**
* How TO Use :
* var sExample = "1";
* var sResult = sPlusOne(sExample.split("")); // result : 2
* Why :
* When you want to add one to a number over Integer. ex) adding menu in order.
*/
var sPlusOne = function( aInputArray ){
var aArray = $.merge([], aInputArray);
var iLength = aArray.length;
if( aArray[iLength-1] == 9 ){
aArray[iLength-1] = 0;
if( iLength == 1 ){
aArray.unshift(1);
}else{
var i = 2;
while( i <= iLength ){
if( aArray[iLength-i] != 9){
aArray[iLength-i] = parseInt(aArray[iLength-i])+1;
break;
}else{
aArray[iLength-i] = 0;
}
if( i == iLength ){
aArray.unshift(1);
}
i++;
}
}
}else{
aArray[iLength-1] = parseInt(aArray[iLength-1])+1;
}
return aArray.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment