How to Get the Opposite of a Number in Java

The challenge

Given a number, find its opposite.

Examples:

1: -1 14: -14 -34: 34

The solution in Java

We return the number itself multiplied by a negative 1.

public class Solution { public static int opposite(int number) { return number *= -1; } }
Code language: Java (java)

This can be simplified further as:

public class Solution { public static int opposite(int number) { return -number; } }
Code language: Java (java)

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

public class Solution { public static int opposite(int number) { return Math.negateExact(number); } }
Code language: Java (java)

Test cases to validate our solution

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)); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments