我想检查一组数字中出现的具体数字.例如,数字2出现:
input from 1 to 20
output
3 times
Run Code Online (Sandbox Code Playgroud)
另一个例子:
input from 1 to 100
output
19 times
Run Code Online (Sandbox Code Playgroud)
这是我的代码
int count = 0;
string x = "";
string y = "";
string[] arr2 = new string[100000000];
for (int i = 1; i < arr2.Length; i++)
{
arr2[i - 1] = i.ToString();
}
foreach (var item in arr2)
{
for (int digit = 0;digit<item.Length;digit++)
{
if (digit == 2)
count++;
}
}
Console.WriteLine(count);
Run Code Online (Sandbox Code Playgroud)
我的代码不起作用,但我不知道问题出在哪里.
注意:这必须仅使用for/ foreachloops,而不是使用Dictionary或LINQ或DivRem.
一种有效而简洁的方法是用来Aggregate计算你的计数,而不是计算然后求和或类似(这种方法只需要一次通过数组):
arr2.Aggregate(0, (total, s) => total + s.Count(c => c == '2'))
Run Code Online (Sandbox Code Playgroud)
这在功能上等同于:
int total = 0;
foreach (string s in arr2)
total += s.Count(c => c == '2');
Run Code Online (Sandbox Code Playgroud)
如果您不想使用Linq或扩展方法,那么您可以使用上面的代码并展开剩余的扩展方法:
int total = 0;
foreach (string s in arr2)
{
foreach (char c in s)
{
if (c == '2')
total++;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,string在处理数字之前将数字转换为s有点浪费 - 您可以使用模数和除法运算符来执行此操作%并/直接检查数字(请注意,此代码需要进行小调整才能使用负数):
int total = 0;
foreach (int i in somearrayofnumbers)
{
while (i != 0)
{
if (i % 10 == 2)
total++;
i /= 10;
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,为了完成 - 我能想到的最好的方法是上面的混合:
int CountDigits(int in, int val)
{
int total = 0;
while (in != 0)
{
if (in % 10 == val)
total++;
in /= 10;
}
return total;
}
...
int digitCount = numbers.Aggregate((total, i) => total + CountDigits(i, 2));
Run Code Online (Sandbox Code Playgroud)
使用Math.DivRem是相当不可读的,因此坚持%和/上面.
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |