while문 종료 후..
조회수 609회
public int solution(int num) { int answer = num; int cnt = 0;
while (answer > 1){
if (answer % 2 == 0) {
cnt++;
answer = answer / 2;
}
if (answer % 2 == 1) {
cnt++;
answer = answer * 3 + 1;
}
if (cnt == 500) {
cnt = -1;
break;
}
}
System.out.println(cnt);
return cnt;
}
main은 생략하였습니다. answer값이 1이 되는 과정을 카운팅하고 카운팅 값을 리턴하고싶은데요..
breakpoint를 while에 찍은 후 디버깅 시 while문이 끝난 후 cnt를 리턴하지 못하고 종료된건지 어쩐건지 멈춰버립니다..
그냥 실행해서 num에 6을 입력하면 -1이 출력되구요..
return 위 print는 디버깅 용도로 넣어놨는데 저기 타지도 않고 while문 종료 후 디버깅이 멈춰버립니다. 왜그런걸까요..? 그리고 그냥 run하면 6 입력 시 -1이 찍히는 걸까요..원래 출력되어야하는 값는 8입니다. 도통모르겠어서 질문남깁니다..
2 답변
-
answer가 첫 if문에서 변경된 후 두번째 if문에 의해 한번 더 변경되어 문제가 발생하였습니다. 다시 값이 증가하여 무한루프에 빠지게 되고 cnt == 500 조건에 의해 cnt는 -1로 변경되었습니다.
else를 추가해주시기 바랍니다.
public int solution(int num) { int answer = num; int cnt = 0; while (answer > 1){ if (answer % 2 == 0) { cnt++; answer = answer / 2; } // 이 부분에서 answer가 1이 됩니다. 그 후 if문에 의해 다시 4가 됩니다. /*else*/ if (answer % 2 == 1) { cnt++; answer = answer * 3 + 1; } if (cnt == 500) { cnt = -1; break; } } System.out.println(cnt); return cnt; }
-
(•́ ✖ •̀)
알 수 없는 사용자
-
-
댓글 입력