728x90

✨number 의 부호를 알아내기 위한 helper method

기본적으로 양수(positive) 또는 음수(negative) 1을 반환하며(+/- 1), 괄호 안에 0을 넣는다면 +/- 0을 반환한다.
(양수는 +로 표기하지 않고 생략한다)
Reverse Int(숫자 거꾸로 바꾸기) Algorithm에서 유용하게 사용했다.
(number를 string으로 바꿔 다루는 경우, 최종값은 number로 반환해야 하기 때문에 부호를 되찾을 때 사용한다)

💻Example Code

const num = -24;

console.log( Math.sign(num) );

실행 결과 (-1)

😋 Reverse Int algorithm을 다룰 때, test case로 주어진 number값을 string으로 변환 후 순서를 뒤바꿔 줘야한다.
따라서, 마지막 결과값을 return 해줄 때, Math.sign(test case값)을 곱해주면 본래의 부호를 손쉽게 다시 되찾을 수 있다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Number.prototype.toString()  (0) 2019.12.24
Global.parseInt()  (0) 2019.12.24
Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22

+ Recent posts