Codility's BinaryGap: Hardware-aware answer This is a well-known question, which some others have posted about on this site.

Here's my first shot following a state machine approach:

int solution(int N) {
    int longestSizeGap{};
    int sizeGap{};
    bool gapStarted{};
    while (N &gt; 0) {
        int remainder{N%2};
        switch (remainder) {
            case 0: {
                if (gapStarted) {
                    sizeGap++;
                }
                break;
            }
            case 1: {
                if (!gapStarted) {
                    gapStarted = true;
                } else {
                    if (sizeGap &gt; longestSizeGap) {
                        longestSizeGap = sizeGap;
                    }
                }
                sizeGap = 0;
                break;
            }
        }
        N /= 2;
    }
    return longestSizeGap;
}


How could I improve this solution to be more "hardware-aware", i.e. what about branch prediction and pipelining, cache misses and page faults, memory hierarchy and data locality? How could I improve my code to just run better?
Scoping the case body is unnecessary.
gapStarted flag is redundant (sizeGap has all the necessary information). Consider

while (N &gt; 0) {
    int remainder{N%2};
    switch (remainder) {
        case 0:
            sizeGap++;
            break;
        case 1:
            if (sizeGap &gt; longestSizeGap) {
                longestSizeGap = sizeGap;
            }
            sizeGap = 0;
            break;
        }
    }
    N /= 2;
}

To address your immediate concerns, there is too few variables to worry about cache, pages, or memory hierarchy. Everything will stay in registers. I don't think you can do anything about branch prediction; however, read the next bullet.
A nice to know approach is de Bruijn hashing:


find the length of trailing gap using a technique described in the answer
remember the length
shift the number left by that length
find the number of trailing ones (e.g. negate and find the number of trailing zeroes), and shift them off
keep going until the number becomes 0.


Such loop will do as many iterations as there are gaps, as opposed to the argument width in your code. Worst case is still the same. OTOH, notice that there is no branches at all.