如何在整数中找到9的个数

joh*_* Gu 7 c#

我有以下方法,应该在整数中找到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;
    }
}
Run Code Online (Sandbox Code Playgroud)

其中我试图找到传递的整数中有多少9个,但上面的方法将始终返回零.什么出了什么问题?

Syn*_*der 23

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

public int GetAmountOfNine(int i)
{
    return i.ToString().Count(c => c.Equals('9'));
}
Run Code Online (Sandbox Code Playgroud)

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

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

例:

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

foreach (var b in bytes)
{
    Console.Write(b); 
}
Run Code Online (Sandbox Code Playgroud)

安慰:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • @BradChristie`string`实现`IEnumerable <char>`. (4认同)
  • 我认为你的意思是"Where"而不是"Select",但更重要的是,你可以使用`.Count(c => c.Equals('9'))`等效. (3认同)
  • 如果您向OP _Why_解释他的初始尝试不起作用,这个答案会更有用. (2认同)

小智 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;
}
Run Code Online (Sandbox Code Playgroud)

这是如何运作的? 考虑一个例子,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

  • 我喜欢这个意外地用于`int.MinValue`的方式,它在被否定时保持负值,但是在base10中它的零值仍然是零,所以它仍然可以运行. (7认同)
  • @SynerCoder和`<< =`,`>> =`,`| =`,`&=`和`^ =`,来自我的头顶 (2认同)