You can either be inside a UTF-8 char or outside. Judging by that there are only few conditions that have to be met.

```
class Solution {
public boolean validUtf8(int[] data) {
int contBytes = 0;
for (int dat : data) {
int bits = countLeadingBits(dat);
if (contBytes <= 0) {
// a new UTF-8 char begins
if (bits == 1 || bits > 4) return false;
contBytes = bits - 1;
} else {
// byte is supposed to start with 10
if (bits != 1) return false;
contBytes--;
}
}
return contBytes <= 0;
}
private int countLeadingBits(int num) {
int bits = 0;
for (int i=7; i >= 0; i--) {
if(((num >> i) & 1) == 1) bits++;
else break;
}
return bits;
}
}
```