forked from GauravWalia19/Algorithms-and-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryToDecimal.c
More file actions
38 lines (38 loc) · 726 Bytes
/
Copy pathbinaryToDecimal.c
File metadata and controls
38 lines (38 loc) · 726 Bytes
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
/**
* RUNNING TESTCASES
* 11111 -> 31
* 10011 -> 19
* 1111111111111111111 -> 524287
* valid upto 19 digits
*/
#include <stdio.h>
#include <math.h>
int binaryToDecimal(long long n)
{
int result = 0;
int i = 0;
while(1)
{
if (n == 0)
{
break;
}
int rem = (int)(n % 10);
if (rem != 0 && rem != 1)
{
return -1;
}
n = n / 10;
result = result + (int)pow(2, i) * rem;
i++;
}
return result;
}
int main()
{
printf("Enter the binary number\n");
long long num;
scanf("%lld", &num);
int result = binaryToDecimal(num);
printf("RESULT: %d\n", result);
}