I am doing code challenge where given two integers l
and r
, I have to print all the odd numbers between i
and r
(i
and r
inclusive). The function must return an array of integers denoting the odd numbers between l
and r
.
This is what I have so far
static int[] oddNumbers(int l, int r) {
int[] theArray = new int[r];
for (int i = l; i < theArray.length; i++) {
if (i % 2 != 0) {
for (int n = 0; n < theArray.length; n++) {
theArray[n] = i;
}
}
}
return theArray;
}
So at the moment this code if you give it values 2 and 5 should return 3,5. However, this only returns 33333. What am I doing wrong? And how can I improve this code?
We are in 2018 and do already have the amazing Streams
since Java 8! With that you can solve such things in a single line! So it's worth it to take a look at it:
static int[] oddNumbers(int i, int j){
return IntStream.rangeClosed(i, j).filter(num -> num % 2 == 1).toArray();
}
(unless you really want to learn algorithms and not just solve the challenge!)
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