forked from annuraagggIIIT/Problem-Solving
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarytodecimal.cpp
More file actions
93 lines (79 loc) · 1.54 KB
/
binarytodecimal.cpp
File metadata and controls
93 lines (79 loc) · 1.54 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
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
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
int searchDecimal(string &str)
{
size_t position = str.find('.');
if (position != string::npos)
{
return position;
}
else
{
return -1;
}
}
double binaryToDecimal(string &str)
{
int startPower = str.length() - 1;
// search the decimal and set index accordingly
int decimalPos = searchDecimal(str);
if (decimalPos != -1)
{
startPower = decimalPos - 1;
}
double decimalValue = 0;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == '1')
{
decimalValue += 1 * pow(2, startPower);
startPower--;
}
else if (str[i] == '.')
{
continue;
}
else if (str[i] == '0')
{
decimalValue += 0 * pow(2, startPower);
startPower--;
}
}
return decimalValue;
}
bool isValid(string &str)
{
int dotCount = 0;
for (int i = 0; i < str.length(); i++)
{
if (str[i] != '0' && str[i] != '1' && str[i] != '.')
{
return false;
}
if (str[i] == '.')
{
dotCount++;
}
}
if (dotCount > 1)
{
return false;
}
return true;
}
int main()
{
string str;
cout << "Enter a binary number: ";
cin >> str;
if (!isValid(str))
{
cout << "Invalid input!"<<endl;
return 0;
}
cout <<"Decimal: "<<binaryToDecimal(str)<<endl;;
return 0;
}