Created
May 15, 2012 00:49
-
-
Save calebds/2698315 to your computer and use it in GitHub Desktop.
Increment an integer represented by an int array
This file contains hidden or 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
/** | |
* 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