Write a method that returns the index of the last value in the array that is a multiple of 3.
For example, in the array
[4, 7, 9, 7, 12] the last multiple of three is ‘12’, which occurs at index 4.
This is my code so far. Could anyone help me revising my code?
public int findMultipleOfThree(int[] arr)
{
int result = 0;
for (int i = arr.length-1; i > 0; i--)
{
if(i%3==0)
{
result = arr[i];
}
}
return result;
}
I know this is far from the right answer. Please help
You have switched the element for comparison and result, you need to
if (arr[i] % 3 == 0)result = ibest: you can do it from the end, and return the first match, you do the minimum iteration
public static int findMultipleOfThreeBackward(int[] arr) {
for (int i = arr.length - 1; i > 0; i--) {
if (arr[i] % 3 == 0) {
return i;
}
}
return -1;
}
You can do it from the beginning and override result to return the last one
public static int findMultipleOfThreeForward(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 3 == 0) {
result = i;
}
}
return result;
}
I'd also suggest to use -1, as it's an unvalid index, it shows you did not find any value that matches the condition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With