The challenge
Given a number, find its opposite.
Examples:
1
2
3

1: 1
14: 14
34: 34

The solution in Java
We return the number itself multiplied by a negative 1.
1
2
3
4
5

public class Solution {
public static int opposite(int number) {
return number *= 1;
}
}

This can be simplified further as:
1
2
3
4
5

public class Solution {
public static int opposite(int number) {
return number;
}
}

There is also a built in method to help with this if you prefer, called Math.negateExact()
:
1
2
3
4
5

public class Solution {
public static int opposite(int number) {
return Math.negateExact(number);
}
}

Test cases to validate our solution
1
2
3
4
5
6
7
8
9
10
11

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class OppositeExampleTests {
@Test
public void tests() {
assertEquals(1, Solution.opposite(1));
assertEquals(0, Solution.opposite(0));
assertEquals(25, Solution.opposite(25));
}
}
