Here is the code we wrote today:
public int[] tenRun(int[] nums) {
boolean seen10 = false; //whether seen a multiple of 10 yet
int val = 0; //the most recent multiple of 10 seen
for(int i=0; i < nums.length; i++) {
if(nums[i] % 10 == 0) {
seen10 = true;
val = nums[i];
}
if(seen10)
nums[i] = val;
}
return nums;
}
We didn't implement this version in class, but here is another approach to the tenRun problem. When it sees a multiple of 10, it uses another loop to change all the values up to the next multiple of 10. I use while loops since I change the indices other than the ++ inside the loop; you can also do this with for loops in Java, but it's normally considered poor form..
public int[] tenRun(int[] nums) {
int i = 0;
while(i < nums.length) {
if(nums[i] % 10 == 0) {
int j = i+1;
while((j < nums.length) && (nums[j] % 10 != 0)) { //go until next multiple of 10
nums[j] = nums[i];
j++;
}
i = j-1; //skip the values we just changed; i++ below moves to the next multiple
}
i++;
}
return nums;
}