vendredi 26 novembre 2021

Change a bunch of numbers into corresponding alphabets

There are five types of bit encoding: 11, 10, 01, 001, 000.The corresponding message for each bit encoding is

11 -> A

10 -> B

01 -> C

001 -> D

000 -> E

The compile result will look like this:

Enter a sequence of bits: 01100001100110
CBEADB

I've wrote this but it can't work.

#include<iostream>
#include<string>
using namespace std;

int main()
{
    int A, B, C, D, E ;
    string code;
    cout << "Enter a sequence of bits: ";
    cin >> code;
    int i = 0;
    while (i < code.length())
    {
        if( code[i]== 1 && code[i + 1]== 1 )
        {
            cout << 'A';
            i += 2;
        }
        else if ( code[i]== 1 && code[i + 1]== 0)
        {
            cout << 'B';
            i += 2;
        }
        else if ( code[i]== 0 && code[i + 1]== 1)
        {
            cout << 'C';
            i += 2;
        }
        else if ( code[i]== 0 && code[i + 1]== 0 && code[ i + 2]== 1)
        {
            cout << 'D';
            i += 3;
        }
        else if ( code[i]== 0 && code[i + 1]== 0 && code[ i + 2]== 0)
        {
            cout << 'E';
            i += 3;
        }
    }
    cout << endl;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire