DEV Community

Joel Okoro
Joel Okoro

Posted on

Codewars Challenge: Opposite Number

This is my approach to the 8kyu challenge labelled Opposite Number. This will be an explanation on how I approached the challenge and came to a solution.

The instructions for this challenge were given a number, find it's opposite. For example, 4 would return -4 , 88 would return -88 and 200.38 would return -200.38. The challenge provides the user a function called opposite which takes in a number parameter, as shown below.

function opposite(number){
/// your code here
}

Initial Approach

I first started by thinking of how I could turn the number that would be passed as an argument into a negative number or an opposite of itself. My initial attempt was to append the string "-" (minus sign) to number and then return it.

function opposite(number){
let newNum = "-" + number;
let oppNum = parseInt(newNum)
return oppNum;
}

The code snippet above had a few problems. One issue was that because of the use of the parseInt() method, decimals or floats would be rounded to the nearest integer e.g. 4.21 would be -4, instead of -4.21.

Final approach & solution

I then realised that I had to think of a way to get the opposite of number without appending any strings or special characters. I knew that in order to get the negative of the number, it would involve subtracting from number from another integer or vice versa. The only integer that would remain constant without changing itself or the argument, as well as guaranteeing that a negative number would be returned regardless of being an integer or float, was 0.

function opposite(number){
let oppNum = 0 - number
return oppNum;
}

Top comments (1)

Collapse
 
craigmc08 profile image
Craig McIlwrath

You could also use the unary negation operator:

function opposite(x) {
  return -x;
}