我想用C#中更优雅的代码来解决这个难题。
using System;
public class Program
{
public static void Main()
{
int numero = 12345678;
int check = CountHoles(numero);
Console.WriteLine(check);
}
public static int CountHoles(int num){
int roles = 0;
for (int i=0; i < num.ToString().Length; i++ ){
string ver = "";
ver = num.ToString().Substring(i,1);
if (ver.Contains("0") || ver.Contains("4") || ver.Contains("6") || ver.Contains("9")){
roles++;
}
if (ver.Contains("8")){
roles = roles+2;
}
}
return roles;
}
}
.Net小提琴:https://dotnetfiddle.net/3s8ucy
谢谢:)
答案 0 :(得分:4)
我喜欢使用字典映射代替if语句。您可以使用LINQ从字符串中获取数字数组,然后使用另一个LINQ语句来对结果求和(或者您可以将两者合并为一个LINQ语句)。
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
private static Dictionary<int, int> _holeMap = new Dictionary<int, int>
{
{ 0, 1 },
{ 1, 0 },
{ 2, 0 },
{ 3, 0 },
{ 4, 1 },
{ 5, 0 },
{ 6, 1 },
{ 7, 0 },
{ 8, 2 },
{ 9, 1 }
};
public static void Main()
{
int numero = 12345678;
int check = CountHoles(numero);
Console.WriteLine(check);
}
public static int CountHoles(int num){
var digits = num
.ToString()
.Select(c => int.Parse(c.ToString()));
return digits.Sum(d => _holeMap[d]);
}
}
答案 1 :(得分:0)
您不需要将数字转换为字符串,您可以像这样改进方法CountHoles
:
int holes = 0;
do{
float tmp = (float) num / 10;
num /= 10;
int ver = (tmp - num) * 10;
if (ver == 0 || ver == 4 || ver == 6 || ver == 9) holes++;
if (ver == 8) holes += 2;
}while (num != 0)
return roles;