Monday, July 24, 2017

Sparse Numbers

I just completed my Codility test, and one of my solutions ran slowly. Unfortunately, I am unable to find out where the bottleneck might be (its hard to cover all possible test cases within a limited time).

But I think it might be the way I get the next sparse number. My Java implementation is below.



    /**
     *
     * @param i assume i to be sparse.
     * @return
     */
    private int getNextSparse(int i) {

        int mask = 0b11;
        int shift = 0;
        while ((i & (mask << shift)) != 0) {
            shift++;
        }

        return (i & (0b11111111_11111111_11111111_11111111 << shift)) | (1 << shift);
    }


I hope to have a YouTube video out to explain all the above soon. (edit: the YouTube vide is here)

No comments:

Post a Comment