From 335d9550012aaa3dc732aa01d46bfd67d3274325 Mon Sep 17 00:00:00 2001 From: antonioialazzo Date: Thu, 30 Oct 2025 18:44:57 +0100 Subject: [PATCH 1/2] binary converter --- exercises/binary_converter.cpp | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/exercises/binary_converter.cpp b/exercises/binary_converter.cpp index 19bf37dd..4aa9ee7c 100644 --- a/exercises/binary_converter.cpp +++ b/exercises/binary_converter.cpp @@ -1,7 +1,23 @@ -/* - Write a program that given a number as input convert it in binary. +#include +#include +#include +using namespace std; - Output: - Insert first number: 8 - The binary number is: 1000 -*/ +string binary_converter(int n){ + string binary = ""; + while (n>0) { + if(n%2) binary.append(1, '1'); + else binary.append(1, '0'); + n=n/2; + } + reverse(binary.begin(), binary.end()); + return binary; +} + +int main () { + int number; + cout << "Insert first number: " << endl; + cin >> number; + cout << "The binary number is: " << binary_converter(number) < Date: Fri, 31 Oct 2025 11:39:37 +0100 Subject: [PATCH 2/2] Added case where input is equal to zero and compacted append function --- exercises/binary_converter.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/exercises/binary_converter.cpp b/exercises/binary_converter.cpp index 4aa9ee7c..99e03e7f 100644 --- a/exercises/binary_converter.cpp +++ b/exercises/binary_converter.cpp @@ -4,10 +4,10 @@ using namespace std; string binary_converter(int n){ + if(!n) return "0"; // if input is zero return "0" string binary = ""; while (n>0) { - if(n%2) binary.append(1, '1'); - else binary.append(1, '0'); + binary.append(1, n % 2 ? '1' : '0'); n=n/2; } reverse(binary.begin(), binary.end()); @@ -19,5 +19,4 @@ int main () { cout << "Insert first number: " << endl; cin >> number; cout << "The binary number is: " << binary_converter(number) <