Last active
April 17, 2020 09:04
-
-
Save GermanAizek/f9da7654a56c252b38de488b0cc5d988 to your computer and use it in GitHub Desktop.
Напишите функцию, которая принимает на вход знаковое целое число и печатает его двоичное представление, не используя библиотечных классов или функций.
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 <vector> | |
template <typename T> | |
auto printBinary(T decimalNumber) -> void | |
{ | |
std::vector<T> result; | |
auto buffer = std::move(decimalNumber); | |
auto intermediateResult = std::move(decimalNumber); | |
if (buffer < 0) | |
{ | |
buffer *= -1; | |
intermediateResult *= -1; | |
result.push_back(1); | |
} | |
else | |
result.push_back(0); | |
while (intermediateResult >= 0) | |
{ | |
intermediateResult = buffer / 2; | |
buffer = buffer % 2; | |
result.push_back(buffer); | |
buffer = intermediateResult; | |
if (intermediateResult == 0) | |
break; | |
} | |
std::reverse(std::begin(result) + 1, std::end(result)); | |
for (auto& binaryRank : result) | |
std::cout << binaryRank << ' '; | |
} | |
int main() | |
{ | |
printBinary<int32_t>(0); | |
std::cout << "\n\n"; | |
printBinary<int>(10); | |
std::cout << "\n\n"; | |
printBinary<signed int>(-10); | |
std::cout << "\n\n"; | |
printBinary<int64_t>(228); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment