forked from CoderAcademy-BRI/ruby-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path36_binary_flip.rb
More file actions
50 lines (39 loc) · 1.12 KB
/
Copy path36_binary_flip.rb
File metadata and controls
50 lines (39 loc) · 1.12 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
# Task
# You are given a binary string (a string consisting of only '1' and '0').
# The only operation that can be performed on it is a Flip operation.
# It flips any binary character ( '0' to '1' and vice versa)
# and all characters to the right of it.
# For example, applying the Flip operation to the 4th character of string "1001010"
# produces the "1000101" string, since all characters from the 4th to the 7th are flipped.
# Your task is to find the minimum number of flips required to convert
# the binary string to string consisting of all '0'.
# Example
# For s = "0101", the output should be 3.
# It's possible to convert the string in three steps:
# "0101" -> "0010"
# ^^^
# "0010" -> "0001"
# ^^
# "0001" -> "0000"
def flip(string, index)
while index < string.size
if string[index] == "1"
string[index] = "0"
else
string[index] = "1"
end
index += 1
end
end
def bin_flip(binary_string)
flips_used = 0
i = 0
while i < binary_string.length
if binary_string[i] == "1"
flip(binary_string, i)
flips_used += 1
end
i += 1
end
return flips_used
end