C++ uses loops to check bit set. Do not need to convert binary to hex or decimal.


  • 0
    B

    This can apply to a character with all 8 bits set.

    class Solution {
    public:
        bool validUtf8(vector<int>& data) {
            for(int i=0;i<data.size(); )
            {
                int j = 0;
                while(j<=7 &&  data[i] & (1<<(7-j)) ){ // check jth bit from most significant bit to least
                    j++;
                } // The character has j most significant bits set. 
                if(j==0) { // character starting with 0b0
                    i++;
                    continue;
                }
                if(j==1) return false; // character starting with 0b10
                for(int k=1;k<j;k++) // We need to check the following j-1 bytes.
                {
                    if(i+k < data.size() && (data[i+k] & 0b11000000) == 0b10000000) continue; // need to check if i+k < data.size()
                    else return false;
                }
                i+=j;
            }
            return true;
        }
    };
    

Log in to reply
 

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