Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i find the number of 9s in an integer

Tags:

c#

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?

like image 982
john Gu Avatar asked Oct 18 '12 20:10

john Gu


People also ask

Is nine a integer number?

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.

How many 9s are there from 0 to 100?

There are total 20 nines between 1–100.

How many times digit 9 will appear in the integers from 1 to 1000?

Answer: The answer is ‎300.

How do you find the number of digits in an integer?

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.


1 Answers

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;
}
like image 115
SynerCoder Avatar answered Oct 20 '22 07:10

SynerCoder