-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday3_set2.cpp
More file actions
56 lines (47 loc) · 1.05 KB
/
day3_set2.cpp
File metadata and controls
56 lines (47 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
using namespace std;
int tobinary(int n)
{
int ans = 0;
int pow = 1;
while (n > 0)
{
int rem = n % 2;
n /= 2;
ans += (rem * pow);
pow *= 10;
}
return ans;
// can also be done using for loop but while is more easy to implement
}
int todecimal(int n)
{
int ans = 0;
int pow = 1;
while (n > 0)
{
int rem = n % 10; // just a change of logic , replace 2 by 10 in the decimal to binary
n /= 10;
ans += rem * pow;
pow *= 2;
}
return ans;
}
int main()
{
// Binary number system
// 1. decimal to binary : front to back and back to front number display
int n, num;
cout << "Enter a number : ";
cin >> n;
cout << "decimal to binary series :: ";
for (int i = 0; i <= n; i++)
{
cout << tobinary(i) << endl;
}
cout << "single term :: " << tobinary(n) << endl;
cout << "Enter a binary number :: ";
cin >> num;
cout << "binary to decimal " << todecimal(num) << endl;
return 0;
}