From 8bbeaecf94d4e08f91499ee0a65fbfaef1db32e2 Mon Sep 17 00:00:00 2001 From: extragit Date: Wed, 5 Nov 2025 18:01:11 +0100 Subject: [PATCH 1/2] feat: Implemented Binary Converter --- exercises/binary_converter.cpp | 45 +++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/exercises/binary_converter.cpp b/exercises/binary_converter.cpp index 19bf37dd..4f1c379d 100644 --- a/exercises/binary_converter.cpp +++ b/exercises/binary_converter.cpp @@ -1,7 +1,44 @@ /* - Write a program that given a number as input convert it in binary. + Write a program that given a number as input convert it in binary. - Output: - Insert first number: 8 - The binary number is: 1000 + Output: + Insert first number: 8 + The binary number is: 1000 */ +#include + +using namespace std; + +void BinR(unsigned long int num){ + if(!num){ + return; + } + + if(num%2){ + BinR((num-1)/2); + cout<< "1"; + return; + } + + BinR(num/2); + cout<< "0"; + return; +} + +int main(){ + unsigned long int num; + + cout << "Insert first number: "; + cin >> num; + + if(cin.fail()){ + cerr << "Error: The given value is not a number" << endl; + exit(1); + } + + cout<< "The binary number is: "; + BinR(num); + + cout << endl; + return 0; +} From 988da0c866649429550242cc16f2154b98c88d4c Mon Sep 17 00:00:00 2001 From: extragit Date: Wed, 5 Nov 2025 18:21:37 +0100 Subject: [PATCH 2/2] Fix: Now work with negative numbers --- exercises/binary_converter.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/exercises/binary_converter.cpp b/exercises/binary_converter.cpp index 4f1c379d..cc4a7414 100644 --- a/exercises/binary_converter.cpp +++ b/exercises/binary_converter.cpp @@ -9,7 +9,7 @@ using namespace std; -void BinR(unsigned long int num){ +void BinR(long int num){ if(!num){ return; } @@ -26,7 +26,7 @@ void BinR(unsigned long int num){ } int main(){ - unsigned long int num; + long int num; cout << "Insert first number: "; cin >> num; @@ -36,6 +36,11 @@ int main(){ exit(1); } + if(num < 0){ + num *= -1; + cout<< "Warning: The given value is a negative number. Switching to "<< num << endl; + } + cout<< "The binary number is: "; BinR(num);