Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream counting Operation until An integer becomes 0

How do I use Java Stream given an integer N of which actions are, if N is odd, subtract 1 from it and if N is even, divide it by 2 until N becomes 0?

This is my working code using procedural style:

public static int solution(int num) {
    int counter = 0;
    while(num != 0) {
        num = (num % 2 == 0) ? num / 2 : num - 1;
        counter++;
    }

    return counter;
}
like image 545
Julez Avatar asked Mar 19 '26 18:03

Julez


1 Answers

You can use IntStream.iterate with the same logic:

public static long solutionStream(int num) {
    return IntStream.iterate(num, i -> i % 2 == 0 ? i / 2 : i -1)
            .takeWhile(i -> i > 0)
            .count();
}

Just note that takeWhile is only available in Java 9+, and it's necessary here to end the infinite stream produced by iterate.

like image 50
ernest_k Avatar answered Mar 21 '26 07:03

ernest_k