shared my C++ solutions, easy to understand.


  • 0
    J

    just share my code

    class Solution {
    public:
        bool isOne(int num, int k) {
            int flag = 1 << (8-k);
            return num & flag;
        }
        
        bool isOneZero(int num) {
            return isOne(num, 1) && (!isOne(num, 2));
        }
        
        bool isOneOneZero(int num) {
            return isOne(num, 1) && isOne(num, 2) && (!isOne(num, 3));
        }
        
        bool isOneOneOneZero(int num) {
            return isOne(num, 1) && isOne(num, 2) && isOne(num, 3) && (!isOne(num, 4));
        }
        
        bool isOneOneOneOneZero(int num) {
            return isOne(num, 1) && isOne(num, 2) && isOne(num, 3) && isOne(num, 4) && (!isOne(num, 5));
        }
    
        bool validUtf8(vector<int>& data) {
            int size = data.size();
            if(size == 0)
                return false;
            int index = 0;
            for(int index = 0; index < size;) {
                if(!isOne(data[index], 1)) {
                    index ++;
                } else if (isOneOneZero(data[index])) {
                    if(isOneZero(data[index+1])) 
                        index += 2;
                    else 
                        return false;
                } else if (isOneOneOneZero(data[index])) {
                    if(isOneZero(data[index+1]) && isOneZero(data[index+2]))
                        index += 3;
                    else 
                        return false;
                } else if (isOneOneOneOneZero(data[index])) {
                    if(isOneZero(data[index+1]) && isOneZero(data[index+2]) && isOneZero(data[index+3]))
                        index += 4;
                    else 
                        return false;
                } else
                    return false;
            }
            return true;
        }
    };
    

Log in to reply
 

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