描述:
返回一个数字在数组里出现的次数
例如:
var sample = { 1, 0, 2, 2, 3 };
NumberOfOccurrences(0, sample) == 1;
NumberOfOccurrences(2, sample) == 2;
MyCode:
using System;
public class OccurrencesKata
{
public static int NumberOfOccurrences(int x, int[] xs)
{
int count = 0;//定义要返回的出现次数
foreach(int i in xs)//遍历数组里的每个整数,若与x相等,则count+1
{
if(x == i)
count++;
}
return count;
}
}
CodeWar:
using System;
using System.Linq;
public class OccurrencesKata
{
public static int NumberOfOccurrences(int x, int[] xs)
{
return xs.Count(num => num == x);
}
}