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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With