我有以下方法,应该在整数中找到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)
小智 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