Java concise code and straightforward logic


  • 0
    L
        public boolean validUtf8(int[] data) {
            int maskFirst = 0x0080, maskFirst2 = 0x00C0, maskFirst3 = 0x00E0, maskFirst4 = 0x00F0;
            int mask = 0, count = 0;
            for(int i = 0; i < data.length; i++){
                if(count == 0 && (maskFirst & data[i]) == 0) continue;
                if(count > 0){
                    if((maskFirst & data[i]) == 0) return false;
                    count--;
                }else if((maskFirst4 & data[i]) == maskFirst4 && (data[i] & 0x0008) != 0x0008){
                    count = 3;
                }else if((maskFirst3 & data[i]) == maskFirst3 && (data[i] & 0x0010) != 0x0010){
                    count = 2;
                }else if((maskFirst2 & data[i]) == maskFirst2 && (data[i] & 0x0020) != 0x0020){
                    count = 1;
                }else{
                    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.