-
Notifications
You must be signed in to change notification settings - Fork 0
/
numberConversionUsingFunctions.cpp
123 lines (93 loc) · 2.16 KB
/
numberConversionUsingFunctions.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include<bits/stdc++.h>
// #include<iostream>
#include<cmath>
using namespace std;
int binaryToDecimal(int num){
// int exp = 0;
int mul = 1;
int ans = 0;
while(num > 0){
// int lastDigit = num%10;
// ans = ans + (lastDigit*pow(2, exp));
// exp = exp+1;
// num = num/10;
int lastDigit = num%10;
ans = ans + (lastDigit*mul);
mul = mul*2;
num = num/10;
}
return ans;
}
int octalToDecimal(int num){
int mul = 1;
int ans = 0;
while(num > 0){
int lastDigit = num%10;
ans = ans + (lastDigit*mul);
mul = mul*8;
num = num/10;
}
return ans;
}
int hexaDecimalToDecimal(string num){
int mul = 1;
int ans = 0;
int size = num.size();
for(int i = size-1; i >=0; i--){
if(num[i] >= '0' && num[i] <= '9'){
ans = ans + mul*(num[i]-'0');
} else if(num[i] >= 'A' && num[i] <= 'F'){
ans = ans + mul*(num[i] - 'A' + 10);
}
mul = mul * 16;
}
return ans;
}
int decimalToBinary( int num ){
int mul = 1;
int res = 0;
while(num > 0){
int rem = num % 2;
res = res + mul*rem;
mul = mul*10;
num = num / 2;
}
return res;
}
int decimalToOctal(int num){
int mul = 1;
int res = 0;
while( num > 0){
int rem = num % 8;
res = res + rem*mul;
mul = mul*10;
num = num / 8;
}
return res;
}
string decimalToHexadecimal(int num){
string ans = "";
while(num > 0){
char digit = '0';
int rem = num % 16;
if(rem <= 9){
digit = rem + '0';
} else {
digit = rem + 'A' - 10;
}
ans.push_back(digit);
num = num / 16;
}
string temp = ans;
for(int i = 0; i < ans.size(); i++){
ans[i] = temp[ans.size() - i - 1];
}
return ans;
}
int main(){
int n;
// string n; //Only for hexadecimalToDecimal
cin>>n;
cout<<decimalToHexadecimal(n)<<endl;
return 0;
}