forked from Rohit91singh9/Coding-DP-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString_Containing_Binary.c
More file actions
108 lines (57 loc) · 1.95 KB
/
String_Containing_Binary.c
File metadata and controls
108 lines (57 loc) · 1.95 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include<stdio.h>
#include<string.h>
#include<math.h>
//function that takes in String and returns an int
int solution(char *S) {
//we store the length of string S in N
int N=strlen(S);
int count=0, number=0,bit=0,j=0;
//traversing S from the end
for(int i=N-1;i>=0;i--) {
//convert S[i] to integer
bit=S[i]-'0';
//converting binary to decimal form
number = number + (pow(2,j) * bit);
//increasing power of 2 as we move from right to left
j++;
}
//while the number is greater than 0
while(number>0) {
//if number is even
if(number%2==0) {
//divide it by 2
number=number/2;
}
//if number is odd
else
//decrement it by 1
number = number -1;
//increment count in every iteration
count++;
}
//returning count
return count;
}
//main method for testing
int main() {
//calling above function with a sample string of decimal value 28
printf("%d",solution("011100"));
}
// OUTPUT
// 7 Process exited after 8.975 seconds with return value 0.
// ...Program finished with exit code 0
/*Explaination
Importing the string and math modules to use strlen() and pow()
count is used to count the number of operation to make the number 0
Number stores the decimal eqquivalent of given binary
bit is used to the numerical form of each bit in string
j is used to increase the power of 2 for binary to decimal conversion
*/
/* NOTE:
I completed this Assessment during Amazon Hackerrank 1st Round
If you can figure out any other Approach to solve this problem,
feel free to share me the Code which will help other candidate.
I would love to hear from you on the Mail ID I have Provided.
if you've cracked the Interview.
beingactual@gmail.com
*/