DEV Community

Abubakar Sadiq Ismail
Abubakar Sadiq Ismail

Posted on

Day 7 I4G 10DaysofCodeChallenge

Problem: UTF-8 Validation
Category: Medium
Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).

A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

For a 1-byte character, the first bit is a 0, followed by its Unicode code.
For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.

For UTF-8 we are going to check 4 bytes long that n=1,2,3,4..
1 | 0xxxxxxx
2 | 110xxxxx 10xxxxxx
3 | 1110xxxx 10xxxxxx 10xxxxxx
4 | 11110xxx 10xxxxxx 10xxxxxx
10xxxxxx

Example

Input: data = [197,130,1]
Output: true
Explanation: data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
Solution
For Each interger in the input array
1.Convert to 8 bits binary representation.
For the integer 197 = 11000101

Check for n = 1,2,3 conditions.
and return the result.

Problem
Solution Implementation

Top comments (0)