Java Bit Manipulation


  • 0
    Y
    public class Solution {
        public boolean validUtf8(int[] data) {
            if (data == null || data.length == 0) return true;
            for (int i = 0; i < data.length; ) {
                int len = 0;
                if ((data[i] & 0x80) == 0) i ++;
                else {
                    int j = 0x80;
                    while ((data[i] & j) > 0) {
                        j = j >> 1;
                        len ++;
                        if (len > 4) return false;
                    }
                    if (len == 1) return false;
                    i ++;
                    len --;
                    while (len > 0 && i < data.length) {
                        len --;
                        if ((data[i] & 0xC0) != 0x80) return false;
                        i ++;
                    }
                    if (len > 0) return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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