The challenge
Create a function that finds the integral of the expression passed.
In order to find the integral all you need to do is add one to the exponent
(the second argument), and divide the coefficient
(the first argument) by that new number.
For example for 3x^2
, the integral would be 1x^3
: we added 1 to the exponent, and divided the coefficient by that new number).
Notes:
- The output should be a string.
- The coefficient and exponent is always a positive integer.
Examples
3, 2 --> "1x^3"
12, 5 --> "2x^6"
20, 1 --> "10x^2"
40, 3 --> "10x^4"
90, 2 --> "30x^3"
The solution in Java code
public class Solution {
public static String integrate(int coefficient, int exponent) {
int first = ++exponent;
coefficient /= first;
return coefficient+"x^"+first;
}
}
A single line solution:
public class Solution {
public static String integrate(int coefficient, int exponent) {
return coefficient / ++exponent + "x^" + exponent;
}
}
A solution using String.format()
:
class Solution {
static String integrate(int coefficient, int exponent) {
return String.format("%sx^%s", coefficient / ++exponent, exponent);
}
}
Test cases to validate our Java solution code
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
@Test
public void exampleTests() {
assertEquals("1x^3", Solution.integrate(3,2));
assertEquals("2x^6", Solution.integrate(12,5));
assertEquals("10x^2", Solution.integrate(20,1));
assertEquals("10x^4", Solution.integrate(40,3));
assertEquals("30x^3", Solution.integrate(90,2));
}
}