After the end of the sentence...

Asked 2 years ago, Updated 2 years ago, 23 views

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 is omitted. I'd like to count the process in which the answer value becomes 1 and return the count value.
When debugging after taking breakpoint with while, it stops somehow without returning the cnt after the while statement.
If you just run it and type 6 in num, -1 is printed out.

I put the print on the return for debugging purposes, but the debugging stops after the while statement ends. Why is that? And if I just run, will I get minus 1 when I input 6?The original output value is 8. I have no idea, so I'm leaving a question.

java

2022-09-20 19:47

2 Answers

After the answer was changed from the first if statement, the problem occurred because it was changed once more by the second if statement. The value increased again to fall into an infinite loop, and cnt was changed to -1 by the condition cnt == 500.

Please add else.

public int solution(int num) { 
    int answer = num; int cnt = 0;
    while (answer > 1){
        if (answer % 2 == 0) {
            cnt++;
            answer = answer / 2;
        }
        // This is where the answer is 1. And then it becomes 4 again by the if statement.
        /*else*/ if (answer % 2 == 1) {
            cnt++;
            answer = answer * 3 + 1;
        }

        if (cnt == 500) {
            cnt = -1;
            break;
        }
    }

    System.out.println(cnt);
    return cnt;
} 


2022-09-20 19:47

Thank you so much for your kind reply.


2022-09-20 19:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.