Find the Last Multiple of 3 in an Array using Java

Viewed 765

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

5 Answers

Problem

You have switched the element for comparison and result, you need to

  • check the value if (arr[i] % 3 == 0)
  • return the indice result = i

Solution

  • best: 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;
      }
    

Note

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

Your solution almost works! You need to add a break, but I see others have already noticed this. Here is another simple way to do it (not always the most efficient). Iterate through the whole array and check if the current element is a multiple of 3. Store the max index in a variable and update every time you find a larger value. Return arr[max_index]. The code should look something like this, hope I could help you.

    public static int findMultipleOfThree(int[] arr)
{
    int max_index = -1; //if it does not find a multiple of 3 it will return -1
    for (int i = 0; i < arr.length-1; i++)
    {
        if(arr[i]%3==0)
        {
           if(i>max_index)
             max_index = i;

        }
    }
    return arr[max_index];
}

Update to this :

public class Testing {
    public static void main(String[] args) {
        int[] arr = new int[] { 4, 7, 9, 7, 12 };
        System.out.println(findMultipleOfThree(arr));

    }

    public static int findIndexMultipleOfThree(int[] arr) {
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 3 == 0) {
                index = i;
            }
        }
        return index;
    }

}

Output :

4

It's almost ok, you shoud put a break after this line:

result = arr[i];

And change this:

i%3==0

into this:

arr[i]%3==0

Thus you certainly find the last one. Also, your i should go from arr.length-1 to i >=0, since lists begin at 0

Just loop through the values in reverse and immediatley return upon finding a multiple. If nothing is found and the loop is done, return -1. Additionally, you could modify the method signature to pass in any multiple value e.g. 3.

public class HelloWorld {
    public static void main(String... args) {
        int[] values = { 4, 7, 9, 7, 12 };
        
        System.out.println(findIndexForLastMultipleOf(3, values)); // 4
    }
     
    public static int findIndexForLastMultipleOf(int target, int... values) {
        for (int i = values.length - 1; i >= 0; i--) {
            if (values[i] % target == 0) {
                return i;
            }
        }
        return -1;
    }
}

If you are locating a value, rather than an index, what do you return? You should box your int into an Integer and return null if nothing is a multiple. You could also return an Optional<Integer>, if you decide to stream-filter the array.

public class MathUtils {
    public static void main(String... args) {
        int[] values = { 4, 7, 9, 7, 12 };
        
        System.out.println(findLastMultipleOf(3, values)); // 12
    }
     
    public static Integer findLastMultipleOf(int target, int... values) {
        for (int i = values.length - 1; i >= 0; i--) {
            if (values[i] % target == 0) {
                return values[i];
            }
        }
        return null;
    }
}
Related