-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathMake a binary string zero.cpp
More file actions
58 lines (52 loc) · 980 Bytes
/
Make a binary string zero.cpp
File metadata and controls
58 lines (52 loc) · 980 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Give a binary string S, find the number of operations required to make it zero.
Operations allowed :
1. if the number representing the binary string is even, divide it by 2
2. if the number representing the binary strind is odd, subtract 1 from it.
*/
// Time Complexity : O(n)
// Space Complexity : O(n)
#include<iostream>
using namespace std;
int Makeitzero(string &S)
{
if(S.size()==0)
{
return 0;
}
if(S.size()==1)
{
if(S=="0")
{
return 0;
}
else
{
return 1;
}
}
int st = 0;
while(S[st]=='0')
{
st++;
}
int one = 0, zero = 0;
for(int i = st; i<S.size(); i++)
{
if(S[i]=='1')
{
one++;
}
else if(S[i]=='0')
{
zero++;
}
}
int ans = 2*(one-1) + zero + 1;
return ans;
}
int main() {
string S;
cin>>S;
cout<<Makeitzero(S);
}