-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBase Conversion.cpp
105 lines (96 loc) · 2.04 KB
/
Base Conversion.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
string decimalToBinary(int a)
{
string ans;
while (a)
{
ans = to_string(a % 2) + ans;
a = a / 2;
}
return ans;
}
string binaryToDecimal(int b)
{
int ans = 0, base = 1;
while (b)
{
ans += (b % 10) * base;
base *= 2;
b /= 10;
}
return to_string(ans);
}
string binaryToHexadecimal(int c)
{
string ans = "";
char ch;
while (c)
{
int rem = c % 16;
if (rem < 10)
{
ch = rem + '0';
}
else
{
ch = rem - 10 + 'A';
}
ans = ch + ans;
c = c / 16;
}
return ans;
}
string hexadecimalToDecimal(string d)
{
int ans = 0, base = 1;
for (int i = d.size() - 1; i >= 0; i--)
{
if ('0' <= d[i] && d[i] <= '9')
{
ans = ans + base * (d[i] - '0');
}
else if ('A' <= d[i] && d[i] <= 'Z')
{
ans = ans + base * (d[i] - 'A' + 10);
}
base = base * 16;
}
return to_string(ans);
}
vector<string> convert(int a, int b, int c, string d)
{
vector<string> v;
v.push_back(decimalToBinary(a));
v.push_back(binaryToDecimal(b));
v.push_back(binaryToHexadecimal(c));
v.push_back(hexadecimalToDecimal(d));
return v;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int a, b, c;
string d;
cin >> a >> b >> c >> d;
Solution ob;
vector<string> ans = ob.convert(a, b, c, d);
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << " ";
}
cout << "\n";
}
return 0;
}
// } Driver Code Ends