Reputation: 1050
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;
}
Upvotes: 3
Views: 625
Reputation: 31878
With Java9+ an alternative to ernest's solution could be using IntStream iterate(int seed, IntPredicate hasNext, IntUnaryOperator next)
could be as follows :
public static int solution(int num) {
return (int) IntStream.iterate(num, i -> i > 0, i -> i % 2 == 0 ? i / 2 : i - 1).count();
}
Upvotes: 3
Reputation: 45309
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
.
Upvotes: 6