Issue
I have a list which looks like it: [1, 1, 1, 1]
. The size is known and fixed.
I'd like to increment the list this way:
[1, 1, 1, 1]
[2, 1, 1, 1]
...
[9, 1, 1, 1]
[1, 2, 1, 1]
[2, 2, 1, 1]
...
[9, 9, 1, 1]
[1, 1, 2, 1]
...
[9, 9, 9, 9]
What is the most optimal way to do it? I've build this function but I guess it could be improved :
private static void incr(List<Integer> list) {
int i = 0;
boolean stop = false;
while (i < list.size() && !stop) {
if (list.get(i) < 9) {
list.set(i, list.get(i) + 1);
stop = true;
} else {
list.set(i, 1);
i++;
}
}
}
Solution
- Replace your "stop" with a "break;" statement.
- then you can also use a for loop, so you don't need to define i seperately beforehand.
Not really better but a bit shorter.
private static void incr(List<Integer> list) {
for (int i=0; i <list.size(); i++) {
if (list.get(i) < 9) {
list.set(i, list.get(i) + 1);
break;
}
list.set(i, 1);
}
}
Answered By - Hansli
Answer Checked By - Mary Flores (JavaFixing Volunteer)