How to Get the N-Th Power in Java


The challenge

You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don’t forget that the first element has the index 0.

Let’s look at a few examples:

  • array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
  • array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.

The solution in Java code

public class Solution {
  public static int nthPower(int[] array, int n) {
    return n >= array.length ? -1 : (int) Math.pow(array[n], n);
  }
}

An alternative mapping:

public class Solution {
  public static int nthPower(int[] array, int n) {
    if (n < 0 || n >= array.length) return -1;
    return (int) Math.pow(array[n], n);
  }
}

Test cases to validate our Java code

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.stream.IntStream;

public class SolutionTest {
    @Test
    public void basicTests() {
        assertEquals(-1, Solution.nthPower(new int[] {1,2}, 2)); 
        assertEquals(8, Solution.nthPower(new int[] {3,1,2,2}, 3));
        assertEquals(4, Solution.nthPower(new int[] {3,1,2}, 2));
    }
    
    @Test
    public void advancedTests() {
        assertEquals(9261, Solution.nthPower(new int[] {7,14,9,21,15}, 3));
        assertEquals(169, Solution.nthPower(new int[] {2,7,13,17}, 2));
        assertEquals(50625, Solution.nthPower(new int[] {11,23,3,4,15,112,12,4}, 4));
    }
    
    @Test
    public void moreTests() {
        assertEquals(1, Solution.nthPower(new int[] {2,1,2,1,2,1}, 5));
        assertEquals(-1, Solution.nthPower(new int[] {11,23,3,4,15}, 7));
        assertEquals(-1, Solution.nthPower(new int[] {3,2,1,2,3,1}, 6));
    }
    
    public int nthPowerSol(int[] array, int n) {
      return n >= array.length ? -1 : (int) Math.pow(array[n], n);
    }
    
    private static int randomInRange(int min, int max) {
      int range = (max - min) + 1;     
      return (int)(Math.random() * range) + min;
    }
    
    @Test
    public void randomTests() {
        int[] array = new int[randomInRange(2,5)];
        int n = randomInRange(2,6);
        for (int i = 0; i < 50; i++) {          
          for (int k = 0; k < array.length; k++) {
            array[k] = randomInRange(2,15);  
          }       
          assertEquals(nthPowerSol(array, n), Solution.nthPower(array, n));
        }
    }
}