You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros.
You want to make s equal to target.
In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to
'1' and '1' to '0'.
Return the minimum number of operations needed to makesequal totarget.
Input: target ="10111"Output: 3Explanation: Initially, s ="00000".Choose index i =2:"00 _000_ "->"00 _111_ "Choose index i =0:"_00111_ "->"_11000_ "Choose index i =1:"1 _1000_ "->"1 _0111_ "We need at least 3 flip operations to form target.
Input: target ="101"Output: 3Explanation: Initially, s ="000".Choose index i =0:"_000_ "->"_111_ "Choose index i =1:"1 _11_ "->"1 _00_ "Choose index i =2:"10 _0_ "->"10 _1_ "We need at least 3 flip operations to form target.
classSolution {
publicintminFlips(String target) {
int ans = 0;
char prev ='0';
for (char c : target.toCharArray()) {
if (c != prev) { ans++; prev = c; }
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funminFlips(target: String): Int {
var ans = 0var prev = '0'for (c in target) {
if (c != prev) { ans++; prev = c }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defminFlips(self, target: str) -> int:
ans =0 prev ='0'for c in target:
if c != prev:
ans +=1 prev = c
return ans
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfnmin_flips(target: String) -> i32 {
letmut ans =0;
letmut prev ='0';
for c in target.chars() {
if c != prev { ans +=1; prev = c; }
}
ans
}
}
1
2
3
4
5
6
7
8
9
classSolution {
minFlips(target: string):number {
letans=0, prev='0';
for (constcoftarget) {
if (c!==prev) { ans++; prev=c; }
}
returnans;
}
}