c# solution


  • 0
    C
    public bool ValidUtf8(int[] data)
    {
        int bytesToValidate = 0;
    
        foreach (int num in data)
        {
            if (bytesToValidate == 0)
            {
                int bytesCount = this.GetCharLength(num);
    
                if (bytesCount == 1 || bytesCount > 4)
                    return false;
    
                bytesToValidate = bytesCount;
    
                if (bytesCount > 1)
                    bytesToValidate--;
            }
            else
            {
                int mask = 1 << 1;
                if ((num >> 6) != mask)
                    return false;  
    
                bytesToValidate--;
            }
        }
    
        return bytesToValidate == 0;
    }
    
    private int GetCharLength(int num)
    {
        int count = 0;
    
        int mask = 1 << 7;
        while ((num & mask) != 0)
        {
            num = num << 1;
            count++;
        }
    
        return count;
    }
    

Log in to reply
 

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