A simple logic Java solution


  • 0
    L
    public boolean validUtf8(int[] data) {
        int u1 = 0x00c0, u2 = 0x00e0, u3 = 0x00f0;
        int x0 = 0x0080, x1 = 0x0020, x2 = 0x0010, x3 = 0x0008;
        int u = 0x0080, x = 0x0040;
        int count = 0;
        for(int num: data){
            if(count != 0){
                if((num & u) != u || (num & x) != 0) return false;
                count--;
            }
            else if((num & u1) == u1 && (num & x1) == 0){
                count = 1;
            }else if((num & u2) == u2 && (num & x2) == 0){
                count = 2;
            }else if((num & u3) == u3 && (num & x3) == 0){
                count = 3;
            }else if((num & x0) != 0){
                return false;
            }
        }
        return count == 0;
    }

Log in to reply
 

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