Short Java and C++


  • 0

    I like using "foreach loops". I prefer not to use indexes if I don't have to.

    Java:

    public boolean isOneBitCharacter(int[] bits) {
        int s = 0;
        for (int b : bits)
            s = s == 1 ? 2 : b;
        return s == 0;
    }
    

    C++:

    bool isOneBitCharacter(vector<int>& bits) {
        int s = 0;
        for (int b : bits)
            s = s == 1 ? 2 : b;
        return !s;
    }
    

    Go through the bits and update our status:

    • s = 0 means we just saw a single-bit character (or nothing yet)
    • s = 1 means we just saw the first bit of a double-bit character
    • s = 2 means we just saw the second bit of a double-bit character

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.