Skip to content

Instantly share code, notes, and snippets.

@calebds
Created May 15, 2012 00:49
Show Gist options
  • Save calebds/2698315 to your computer and use it in GitHub Desktop.
Save calebds/2698315 to your computer and use it in GitHub Desktop.
Increment an integer represented by an int array
/**
* Adds one to the integer represented by the input array
*
* @param input
* an array representation of an integer > -1, e.g. {1,2,3}
* @return
* an array representation of the input integer, plus one
*/
int[] addOne(int[] input) {
for (int i = input.length - 1; i >=0; i--) {
if (input[i] < 9) {
input[i]++;
return input; // exit when there's no carry
} else {
input[i] = 0;
}
}
int [] result = new int[input.length + 1]; // carry has no home!
result[0] = 1;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment