How to Get the Opposite of a Number in Java

0 min read 123 words

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;
    }
}

This can be simplified further as:

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():

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

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));
  }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags