You can do it simply with a little linq:
public int GetAmountOfNine(int i) { return i.ToString().Count(c => c.Equals('9')); }
But add using System.Linq; to the cs file.
Your answer does not work, because you convert to bytes, converting a number to bytes does not generate a byte for each digit (via @Servy ) sub>. Therefore, if you write each byte in your array for the / debug console, you will not see your number back.
Example:
int number = 1337; byte[] bytes = BitConverter.GetBytes(number); foreach (var b in bytes) { Console.Write(b); }
Console:
57500
However, you can convert int to string and then check each character in the string if it is nine;
public int GetAmountOfNineWithOutLinq(int i) { var iStr = i.ToString(); var numberOfNines = 0; foreach(var c in iStr) { if(c == '9') numberOfNines++; } return numberOfNines; }
Synercoder
source share