c# 中计算字符串中所有1的和,和为偶数为1,奇数为0
思路:使用 LINQ 来计算字符串中 '1' 的数量
`
public static int CalculateSumOfOnes(string input)
{
// 计算字符串中 '1' 的个数
int count = input.Count(c => c == '1');
// 如果 '1' 的个数是偶数,返回 1;否则返回 0
return count % 2 == 0 ? 1 : 0;
}
public static void Main(string[] args)
{
string input = "1101101"; // 示例字符串
int result = CalculateSumOfOnes(input);
Console.WriteLine($"Result: {result}");
}
`
示例输出 对于 input = "1101101":
'1' 的个数是 4(偶数),因此返回 1。 如果将 input 更改为 "1010101"('1' 的个数是 5,奇数),则输出为 0。