Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions exercises/binary_converter.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
/*
Write a program that given a number as input convert it in binary.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

Output:
Insert first number: 8
The binary number is: 1000
*/
string binary_converter(int n){
string binary = "";
while (n>0) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Che succede se l'input è il numero 0?

if(n%2) binary.append(1, '1');
else binary.append(1, '0');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Una versione un po' più co,patta potrebbe essere

binary.append(1, n % 2 ? '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) <<endl;

}