Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the Last Multiple of 3 in an Array using Java

Tags:

java

arrays

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

like image 699
Grey Avatar asked Mar 09 '26 07:03

Grey


1 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

like image 68
azro Avatar answered Mar 10 '26 20:03

azro