Java流计数操作直到整数变为0

Jul*_*lez 3 java java-stream

如何使用给定整数N的Java流,如果N是奇数,则从中减去1,如果N是偶数,则除以2,直到N变为0?

这是我使用程序样式的工作代码:

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

    return counter;
}
Run Code Online (Sandbox Code Playgroud)

ern*_*t_k 6

您可以使用IntStream.iterate相同的逻辑:

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

请注意,这takeWhile仅适用于Java 9+,并且此处必须结束由此产生的无限流iterate.

  • @nullpointer太棒了!`takeWhile`对我来说更自然.谢谢. (2认同)