-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecimal to any base and vice versa.cpp
More file actions
65 lines (56 loc) · 1.38 KB
/
Decimal to any base and vice versa.cpp
File metadata and controls
65 lines (56 loc) · 1.38 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
57
58
59
60
61
62
63
64
65
Decimal to Any Base :
char reVal(int num) {
if (num >= 0 && num <= 9)
return (char)(num + '0');
else
return (char)(num - 10 + 'A');
}
string fromDeci(long long int inputNum, int base) {
string res = "";
while (inputNum > 0) {
res += reVal(inputNum % base);
inputNum /= base;
}
reverse(res.begin(), res.end());
if (res == "")res = "0";
ll len = 32;
// res = string(len - res.length(), '0') + res;
return res;
}
----------------------------------------------------------------------------------
Any Base to Decimal :
int val(char c) {
if (c >= '0' && c <= '9')
return (int)c - '0';
else
return (int)c - 'A' + 10;
}
long long int toDeci(string str, int base) {
long long int len = str.length(), power = 1, num = 0, i;
for (i = len - 1; i >= 0; i--) {
if (val(str[i]) >= base) {
cout << "INVALID NUMBER!";
return -1;
}
num += val(str[i]) * power;
power = power * base;
}
return num;
}
--------------------------------------------------------------------------------
Convert decimal to Binary String of same lengths :
string decToBinary(long long int n)
{
// Size of an integer is assumed to be len bits
string s;
ll len = 15;
for (int i = len - 1; i >= 0; i--) {
long long int k = n >> i;
if (k & 1) s += '1';
else s += '0';
}
return s;
}
[VERY EASY]
https://codeforces.com/contest/1312/problem/C
soln - https://codeforces.com/contest/1312/submission/74190710