반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

undefined

[프로그래머스] 콜라츠 추측 -JS 본문

Coding Test

[프로그래머스] 콜라츠 추측 -JS

JavaScripter 2022. 5. 19. 23:11
반응형

문제 설명


문제 풀이

function solution(num) {
    let attempt = 0
    while (num !== 1) {
        if(attempt === 500) {
            return -1
        }
        num = num % 2 ? num*3+1 : num/2
        attempt++
    }
    return attempt
}

1. while loop 이용하여 num이 1이 될때 까지 반복

 

2. attempt 500번 넘어가는 수는 -1 리턴

 

3. 콜라츠 추측을 한번 거친 수를 다시 num에 배당

 

4. 시도 1+

 


개선 사항

반응형
Comments