Skip to content

Commit 8bbeaec

Browse files
committed
feat: Implemented Binary Converter
1 parent f8f4676 commit 8bbeaec

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

exercises/binary_converter.cpp

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,44 @@
11
/*
2-
Write a program that given a number as input convert it in binary.
2+
Write a program that given a number as input convert it in binary.
33
4-
Output:
5-
Insert first number: 8
6-
The binary number is: 1000
4+
Output:
5+
Insert first number: 8
6+
The binary number is: 1000
77
*/
8+
#include <iostream>
9+
10+
using namespace std;
11+
12+
void BinR(unsigned long int num){
13+
if(!num){
14+
return;
15+
}
16+
17+
if(num%2){
18+
BinR((num-1)/2);
19+
cout<< "1";
20+
return;
21+
}
22+
23+
BinR(num/2);
24+
cout<< "0";
25+
return;
26+
}
27+
28+
int main(){
29+
unsigned long int num;
30+
31+
cout << "Insert first number: ";
32+
cin >> num;
33+
34+
if(cin.fail()){
35+
cerr << "Error: The given value is not a number" << endl;
36+
exit(1);
37+
}
38+
39+
cout<< "The binary number is: ";
40+
BinR(num);
41+
42+
cout << endl;
43+
return 0;
44+
}

0 commit comments

Comments
 (0)