Something wrong with testcase [240,162,138,147,145], cannot pass it, someone help me.


  • 0
    F

    I just followed the examples showed to write the code. I don't know why I cannot pass this one.

    '''
    public class Solution {
    public boolean validUtf8(int[] data) {
    if(data == null || data.length == 0) {return false;}

        int first = data[0];
        String oct = "00000000";
        String firstBinary = Integer.toBinaryString(first);
        if(firstBinary.length() != 8){
            firstBinary = oct.substring(0, 8 - firstBinary.length()) + firstBinary;
        }
        
        int bits = 0;
        for(int i = 0; i < firstBinary.length(); i++){
            if(firstBinary.charAt(i) == '0') {break;}
            else if(firstBinary.charAt(i) == '1') {bits++;}
        }
        if(bits == 0) {return true;}
        else if(bits == 1 || bits > 4 || data.length < bits) {return false;}
        
        for(int i = 1; i < data.length; i++){
            if(i > bits - 1) {return true;}
            String binary = Integer.toBinaryString(data[i]);
            if(binary.length() != 8){
                binary = oct.substring(0, 8 - binary.length()) + binary;
            }
            if(!binary.startsWith("10")) {return false;}
        }
        
        return true;
    }
    

    }
    '''


Log in to reply
 

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