Created
February 28, 2016 03:31
-
-
Save dgodfrey206/b4b70e8e9bdb2251409e to your computer and use it in GitHub Desktop.
Converting unary to base 10
This file contains hidden or 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 <sstream> | |
| std::string UnaryToBinary(std::string str) { | |
| std::string binary; | |
| binary.reserve(30); | |
| char flag; | |
| for (std::stringstream ss(str); ss >> str; ) { | |
| std::size_t size = str.size(); | |
| if (size <= 2) flag = (size & 1) + '0'; | |
| else { | |
| for (std::size_t i = 0; i < size-2; ++i) { | |
| binary += flag; | |
| } | |
| } | |
| } | |
| return binary; | |
| } | |
| std::string BinaryToBase10(std::string const& binary) { | |
| int result = 0; | |
| for (std::size_t i = 0, size = binary.size(); i < size; ++i) { | |
| if (binary[i] == '1') { | |
| result += 1 << (size - i - 1); | |
| } | |
| } | |
| return std::to_string(result); | |
| } | |
| int main() { | |
| for (std::string line; std::getline(std::cin >> std::ws, line, '#') && line.find('~') == std::string::npos; ) { | |
| std::cout << BinaryToBase10(UnaryToBinary(line)) << '\n'; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment