How can I find the number 9s in an integer

I have the following method, which was to find the total number 9 in integers, the method is used to get the contract type of employees based on the number 9. I tried the following class: -

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; } } 

In which I am trying to find how many 9 are in the passed integer, but the above method will always return zero. Any idea what is going wrong?

+7
source share
3 answers

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; } 
+23
source

The classic solution is as follows: (This is probably the fastest algorithm to find a solution, only O (log n) is required.)

 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; } 

How it works? Consider an example, n = 9943

now ret = 0.

n% 10 = 3, which! = 9

n = n / 10 = 994

n% 10 = 4! = 9

n = 99

n% 10 = 9, so ret = 1

n = 9

n% 10 = 9, so ret = 2

n = 0

+20
source

Try

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

Since a string implements an IEnumerable<char> , you can apply LINQ directly to a string without first converting it to an enumeration of characters.


UPDATE

Converting uint to an array of bytes will not work as expected, since uint does not store the decimal digits of your number directly. The number is stored as a binary number, which is incremented by four bytes. A unit always has four bytes, even if your number has 9 decimal digits.

You can convert a number to a string to get its decimal representation.

+2
source

All Articles