7

我有以下方法,它应该在整数中找到 9 的总数,该方法用于根据 9 的数量检索员工的合同类型。我尝试了以下类:-

public class EmployeeCreditCards
{
    public uint CardNumber(uint i)
    {
        byte[] toByte = BitConverter.GetBytes(i);

        uint number = 0;
        for (int n = 0; n < toByte.Length; n++)
        {
            if (toByte[i] == 9)
            {
                number = number + 1;
            }
        }
        return number;
    }
}

我试图找出传递的整数中有多少个 9,但上述方法将始终返回零。知道出了什么问题吗?

4

3 回答 3

23

你可以用一点 linq 做到这一点:

public int GetAmountOfNine(int i)
{
    return i.ToString().Count(c => c.Equals('9'));
}

但是一定要添加using System.Linq;到cs文件中。

您的答案不起作用,因为您正在转换为字节,将数字转换为字节不会为每个数字生成一个字节(通过@Servy。因此,如果您将数组中的每个字节都写入控制台/调试,您将看不到您的号码。

例子:

int number = 1337;
byte[] bytes = BitConverter.GetBytes(number);

foreach (var b in bytes)
{
    Console.Write(b); 
}

安慰:

57500

但是,您可以将 int 转换为字符串,然后检查字符串中的每个字符是否为 9;

public int GetAmountOfNineWithOutLinq(int i)
{
    var iStr = i.ToString();
    var numberOfNines = 0;
    foreach(var c in iStr)
    {
        if(c == '9') numberOfNines++;
    }
    return numberOfNines;
}
于 2012-10-18T20:42:31.823 回答
20

一个经典的解决方案如下:(可能这是最快的算法找到解决方案,它只需要O(log n)时间。)

private int count9(int n)
{
     int ret = 0;
     if (n < 0)
        n = -n;
     while (n > 0)
     {
         if (n % 10 == 9) ++ret;
         n /= 10; // divide the number by 10 (delete the most right digit)
     }
     return ret;
}

这是如何运作的? 考虑一个例子,n = 9943

现在ret = 0。

n % 10 = 3,其中 != 9

n = n / 10 = 994

n % 10 = 4 != 9

n = 99

n % 10 = 9,所以 ret = 1

n = 9

n % 10 = 9,所以 ret = 2

n = 0

于 2012-10-18T20:44:19.840 回答
2

尝试

int numberOfNines = number.ToString().Where(c => c == '9').Count();

由于字符串实现了IEnumerable<char>,因此您可以将 LINQ 直接应用于字符串,而无需先将其转换为字符枚举。


更新

将 转换uint为字节数组不会按预期方式工作,因为uint不会直接存储您的数字的十进制数字。该数字存储为一个跨越四个字节的二进制数。Aunit总是有四个字节,即使你的数字有 9 个十进制数字。

您可以将数字转换为字符串以获得其十进制表示。

于 2012-10-18T20:43:48.873 回答