1-bit and 2-bit Characters

We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

Example 1:

Input: 
bits = [1, 0, 0]
Output: True

Approach

Java


public class Bit1Bit2Chars {
    public static void main(String[] args) {
        int[] bits = { 100 };
        System.out.println(isOneBitCharacter(bits));
    }

    static boolean isOneBitCharacter(int[] bits) {
        int n = bits.length, i = 0;
        if (n == 1)
            return true;
        int flag = 0;
        while (i < n) {
            if (bits[i] == 1) {
                i = i + 2;
                if (i == n) {
                    flag = 1;
                    break;
                }
            } else {
                i++;
            }
        }
        if (flag == 1)
            return false;
        return true;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

bool isOneBitCharacter(vector<int&bits)
{
    int n = bits.size(), i = 0;
    if (n == 1)
        return true;
    int flag = 0;
    while (i < n)
    {
        if (bits[i] == 1)
        {
            i = i + 2;
            if (i == n)
            {
                flag = 1;
                break;
            }
        }
        else
        {
            i++;
        }
    }
    if (flag == 1)
        return false;
    return true;
}
int main()
{
    vector<intbits = {100};
    if (isOneBitCharacter(bits))
        cout << "true";
    else
        cout << "false";
    return 0;
}


No comments:

Post a Comment