-
Notifications
You must be signed in to change notification settings - Fork 112
/
0393-UTF8Validation.cs
44 lines (38 loc) · 1.26 KB
/
0393-UTF8Validation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//-----------------------------------------------------------------------------
// Runtime: 104
// Memory Usage: 27.3 MB
// Link: https://leetcode.com/submissions/detail/372498118/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _0393_UTF8Validation
{
public bool ValidUtf8(int[] data)
{
int numberOfBytesToProcess = 0;
int mask1 = 1 << 7;
int mask2 = 1 << 6;
foreach (int num in data)
{
if (numberOfBytesToProcess == 0)
{
int mask = mask1;
while ((mask & num) != 0)
{
numberOfBytesToProcess++;
mask >>= 1;
}
if (numberOfBytesToProcess == 0) continue;
if (numberOfBytesToProcess > 4 || numberOfBytesToProcess == 1) return false;
}
else
{
if ((num & mask1) == 0 || (mask2 & num) == 1)
return false;
}
numberOfBytesToProcess -= 1;
}
return numberOfBytesToProcess == 0;
}
}
}