本文共 488 字,大约阅读时间需要 1 分钟。
为了统计二进制串中1的个数,可以通过遍历字符串中的每个字符来实现。这种方法直接且简洁,适合处理二进制串输入。以下是实现代码:
public class Solution { public int hammingWeight(String binaryString) { int count = 0; for (char c : binaryString.toCharArray()) { if (c == '1') { count++; } } return count; }} 步骤解释:
count,用于记录1的个数,初始值为0。这种方法简单高效,能够快速统计二进制串中的1的数量。
转载地址:http://stca.baihongyu.com/