Question about Java continuous number acquisition algorithm.

Asked 2 years ago, Updated 2 years ago, 45 views

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        in.close();

        int sum = 0, max = 0;
        while (n > 0) {
            if (n % 2 == 1) {
                sum++;
                if (sum > max) {
                    max = sum;
                }
            } } else {
                sum = 0;
            }
            n = n / 2;
        }
        System.out.println(max);
    }
 n = n/2; why does this go in?

algorithm java

2022-09-22 20:20

1 Answers

The figure above shows an example of converting decimal to binary. What you're curious about is the code to run the next loop after checking the rest divided by 2.

if (n%2 == 1) divided by {//2
    sum++;
    if (sum > max) {
        max = sum;
    } 
} } else {
    sum = 0;
}
n = n/2; // Divide by 2

If there is no n=n/2, the input value will remain the same, so it will go around the infinite loop under the condition of the while statement (n>0), right? I think you're confused that the input value of n%2 will be updated to the value.


2022-09-22 20:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.