"111"
2
删掉前两个 '1',字符串变成"1",为2的幂。
"1010"
1
删掉第三个字符 '1',字符串变成"100",代表的数是
class Solution: def minCnt(self,s): if s == '1': return False s = s[1:] return s.count('1')
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int minCnt (String s) {
// write code here
int sum = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '1') {
sum++;
}
}
return sum - 1;
}
} classSolution:
defminCnt(self, s: str) -> int:
# write code here
returns.count("1") -1 #计算1的个数并保留一个1 import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int minCnt (String s) {
// write code here
// 创建一个数组记录每一个位置 其右边 包含 "1" 的个数
int len = s.length();
int[] rightOneCount = new int[len];
int count = 0;
for (int i = len - 1; i >= 0; i--){
rightOneCount[i] = count;
if (s.charAt(i) == '1') count++;
}
int index = 0;
int minCount = len;
while (index < len){
if (s.charAt(index) != '1'){
index++;
} else {// 找到左端的 1 开始更新最小操作数
minCount = Math.min(minCount, index + rightOneCount[index]);
}
index++;
}
return minCount;
}
}