Add odd numbers between a closed range to an array

user6248190 :

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?

Tim Biegeleisen :

I would approach this by advancing the lower bound in the range to the next odd number, if not already odd, and then proceeding from there.

static int[] oddNumbers(int l, int r) {
    if (r <= l) return null;

    l = (l % 2) == 0 ? l + 1 : l;
    int size = ((r - l) / 2) + 1;

    int[] theArray = new int[size];

    for (int i=0; i < size; ++i) {
        theArray[i] = l + (i*2);
    }

    return theArray;
}

The real difficulty here is in formulating the logic to map a range of odd numbers onto a flat array. Once we have done this, we can see that populating the array only requires a simple for loop.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74537&siteId=1