Created
April 15, 2020 00:26
-
-
Save servadestroya/2e8030ecd2a80115adde6fcc2505c928 to your computer and use it in GitHub Desktop.
Open you mind
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> | |
// Ejemplo de contador binario usando listas enlazadas | |
template<typename T> | |
struct Node { | |
Node<T>* next; | |
T data; | |
Node(T data, Node<T>* next=nullptr): data(data), next(next) {} | |
}; | |
using BinaryNode = Node<bool>; | |
// Won't increment null pointers | |
void increment_counter(BinaryNode* counter) | |
{ | |
for (auto current_node = counter; current_node != nullptr; current_node = current_node->next) { | |
if (current_node->data == true) { | |
current_node->data = false; | |
if (current_node->next == nullptr) { | |
current_node->next = new BinaryNode(1); | |
break; | |
} | |
} else { | |
current_node->data = true; | |
break; | |
} | |
} | |
} | |
template<typename T> | |
T counter_to_number(BinaryNode* counter) | |
{ | |
T number = 0; | |
T shifted = 1; | |
for (auto current_node = counter; current_node != nullptr; current_node = current_node->next) { | |
number |= (shifted * (current_node->data ? 1 : 0)); | |
shifted = shifted << 1; | |
} | |
return number; | |
} | |
int main() | |
{ | |
char op = 'h'; | |
auto counter = new BinaryNode(0); | |
while (op != '0') { | |
if (op == 'i') { | |
increment_counter(counter); | |
} else if (op == 'p') { | |
std::cout << "Binary form (starting by least significant bit): "; | |
for (auto current_node = counter; current_node != nullptr; current_node = current_node->next) { | |
std::cout << current_node->data ? "1" : "0"; | |
} | |
std::cout << std::endl; | |
std::cout << "Decimal form: " << counter_to_number<int>(counter) << std::endl; | |
} else if (op == 'h') { | |
std::cout << "i: increment counter" << std::endl; | |
std::cout << "p: print counter" << std::endl; | |
std::cout << "h: show this help" << std::endl; | |
std::cout << "0: exit" << std::endl; | |
} else if (op != '0') { | |
std::cout << "'" << op << "'" << "is not a valid option." << std::endl; | |
} | |
std::cin >> op; | |
} | |
std::cout << "puto" << std::endl; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment