Last active
January 15, 2023 09:24
-
-
Save BruJu/1cf550bc86c6f61f03a598f75f30422f to your computer and use it in GitHub Desktop.
Unary.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <optional> | |
class MessageEncoder { | |
std::optional<int> current_digit = std::nullopt; | |
std::string output; | |
public: | |
void accumulate(char letter); | |
[[nodiscard]] const std::string & get_output() const { return output; } | |
private: | |
void accumulate_digit(int digit); | |
}; | |
void MessageEncoder::accumulate(const char letter) { | |
accumulate_digit(letter & 0x40 ? 1 : 0); | |
accumulate_digit(letter & 0x20 ? 1 : 0); | |
accumulate_digit(letter & 0x10 ? 1 : 0); | |
accumulate_digit(letter & 0x08 ? 1 : 0); | |
accumulate_digit(letter & 0x04 ? 1 : 0); | |
accumulate_digit(letter & 0x02 ? 1 : 0); | |
accumulate_digit(letter & 0x01 ? 1 : 0); | |
} | |
void MessageEncoder::accumulate_digit(const int digit) { | |
if (current_digit && *current_digit != digit) { | |
output += ' '; | |
current_digit = std::nullopt; | |
} | |
if (!current_digit) { | |
if (digit == 1) output += "0 "; | |
else output += "00 "; | |
} | |
current_digit = digit; | |
output += '0'; | |
} | |
int main() { | |
std::string message; | |
std::getline(std::cin, message); | |
MessageEncoder encoder; | |
for (const char letter : message) { | |
encoder.accumulate(letter); | |
} | |
std::cout << encoder.get_output() << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment