코딩테스트 - Plus Minus

Jeongpyo Hong·2023년 1월 3일

코딩테스트

목록 보기
5/16

문제
Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal.

Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable.

예시

배열 arr이 주어질 때 arr 배열 요소 중 양수, 음수, 0의 각 비율을 소수점 6자리까지 출력하는 문제이다.

풀이
함수 내에서 plus, minus, zero라는 변수를 선언한 후 for 반복문을 사용하여 조건에 따라 ++ 해주는 방법으로 로직을 작성했다.
그리고 배열의 길이로 나눈 후 toFixed()를 사용하여 소수점 6자리까지의 비율을 계산하여 출력했다.

function plusMinus(arr) {
    // Write your code here
    const len = arr.length;
    let plus = 0;
    let minus = 0;
    let zero = 0;
    for (let i = 0; i < len; i++) {        
        if (arr[i] === 0) {
            zero++;
        } else if (arr[i] > 0) {
            plus++;
        } else {
            minus++;
        }
    }
    console.log((plus/len).toFixed(6))
    console.log((minus/len).toFixed(6))
    console.log((zero/len).toFixed(6))
}

해커랭크의 가장 기본 문제인데 영어로 출제되고 readLine()을 사용하여 한줄씩 출력하는? 로직이 기본적으로 작성되어 있는데 처음 봐서 readLine()에 대해 검색을 해서 살펴본 후에 문제를 풀었다.

코딩테스트는 회사 마다 참고하는 사이트가 달라서 여러 사이트에서 연습해보는 것이 좋을 것 같다.

profile
change & addaption

0개의 댓글