Invert values

Lee·2022년 9월 5일

Algorithm

목록 보기
89/92
post-thumbnail

❓ Invert values

Q. Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.

invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
You can assume that all values are integers. Do not mutate the input array/list.

✔ Solution

//#my solution
function invert(array) {
  return array.map((i)=>{
    return i>=0 ? -Math.abs(i) : Math.abs(i)
  });
}

//#other solution
function invert(array) {
   return array.map( x => x === 0 ? x : -x);
}
profile
Lee

0개의 댓글