본문 바로가기
알고리즘/CodeWars

[CodeWars] javascript - 5kyu - Math Issue 문제 풀이

by TLOWAC 2020. 4. 7.

Title

Math Issue

Description

Oh no, our Math object was "accidently" reset. Can you re-implement some of those functions? We can assure, that only non-negative numbers are passed as arguments. So you don't have to consider things like undefined, null, NaN, negative numbers, strings and so on.

Here is a list of functions, we need:

  • Math.round()
  • Math.ceil()
  • Math.floor()

How Can I Solved

문제 요구사항 정의

Math method 구현

Math.roud
Math.ceil
Math.floor

문제 접근

이 문제는 Bit연산자를 이용하면 쉽게 풀수 있는 문제이며, Bit 연산자 중에서 OR 연산자 '|'를 사용한다.
OR 연산자는 2개의 값 중에 하나라도 1이면, 값이 1이 된다.

비트 연산에서는 소수점에 관한 연산이 불가하므로, 비트 연산을 하기 전에 +0.5 , +1.0 등의 연산을 마무리 해준다.

비트 연산 과정 중에서 값이 소수인 경우, 소수점 아래 숫자는 무시된다.

Math.round

소수점 아래 숫자가 0.5 이상인 경우 반올림 해준다.

number +0.5 | 0

3.6 + 0.5 => 4.1 | 0 => 4

Math.ceil

소수점 아래 숫자를 상관하지 않고, 반올림 해준다.
단, 정수인 경우 반올림을 하지 않는다.

Number.isInteger(number) ? number : number+1 | 0

3 => 3
3.6 + 1.0 => 4.1 | 0 => 4

Math.floor

소수점 아래 숫자를 버린다.

number | 0

3.6 => 3

Solution

Math.round = function(number) {
    return number +0.5 | 0
}

Math.ceil = function(number) {
    return Number.isInteger(number) ? number : number+1 |0
};

Math.floor = function(number) {
    return number | 0
};

댓글