I have the following method which should found the total number of 9 in an integer, the method is used to retrieve the employees' contract type based on the number of 9. i tried the below 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?
9 (nine) is a number, numeral, and glyph that represents the number. It is the natural number that follows 8 and precedes 10. It is an integer and a cardinal number, that is, a number that is used for counting.
There are total 20 nines between 1–100.
Answer: The answer is 300.
The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.
You can do this simple with a little linq:
public int GetAmountOfNine(int i)
{
return i.ToString().Count(c => c.Equals('9'));
}
But do add using System.Linq;
to the cs file.
Your answer isn't working because you are converting to bytes, converting the number to bytes does not generate a byte for each digit (via @Servy). Therefor if you would write every byte in your array to console/debug you wouldn't see your number back.
Example:
int number = 1337;
byte[] bytes = BitConverter.GetBytes(number);
foreach (var b in bytes)
{
Console.Write(b);
}
Console:
57500
You can however convert the int to a string and then check for every character in the string if it is a nine;
public int GetAmountOfNineWithOutLinq(int i)
{
var iStr = i.ToString();
var numberOfNines = 0;
foreach(var c in iStr)
{
if(c == '9') numberOfNines++;
}
return numberOfNines;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With