简体   繁体   中英

count odd and even digits in a number

I try to write program that check the ratio between odd and even digits in a given number. I've had some problems with this code:

static void Main(string[] args)
{
    int countEven = 0 ;
    int countOdd = 0 ;
    Console.WriteLine("insert a number");
    int num = int.Parse(Console.ReadLine());
    int length = num.GetLength;
    for (int i = 0;i<length ; i++)
    {
        if((num/10)%2) == 0)
        int countEven++;
    }
}

any ideas?

The problem is that int does not have a length, only the string representation of it has one.As an alternative to m.rogalski answer, you can treat the input as a string to get all the digits one by one. Once you have a digit, then parsing it to int and checking if it is even or odd is trivial.Would be something like this:

int countEven = 0;
int countOdd = 0;
Console.WriteLine("insert a number");
string inputString = Console.ReadLine();
for (int i = 0; i < inputString.Length; i++)
{
    if ((int.Parse(inputString[i].ToString()) % 2) == 0)
         countEven++;
    else
         countOdd++;
}

Linq approach

Console.WriteLine("insert a number");
string num = Console.ReadLine(); // check for valid number here?
int countEven = num.Select(x => x - '0').Count(x => x % 2 == 0);
int countOdd = num.Select(x => x - '0').Count(x => x % 2 != 0);

Let's assume your input is : 123456
Now all you have to do is to get the modulo from the division by ten : int m = num % 10;
After that just check if bool isEven = m % 2 == 0;
On the end you have to just divide your input number by 10 and repeat the whole process till the end of numbers.

int a = 123456, oddCounter = 0, evenCounter = 0;
do
{
    int m = a % 10;
    switch(m % 2)
    {
        case 0:
            evenCounter++;
            break;

        default: // case 1:
            oddCounter++;
            break;
    }
    //bool isEven = m % 2 == 0;
}while( ( a /= 10 ) != 0 );

Online example

Made a small change to your code and it works perfectly

int countEven = 0;
int countOdd = 0;
Console.WriteLine( "insert a number" );
char[] nums = Console.ReadLine().ToCharArray();
for ( int i = 0; i < nums.Length; i++ )
{
    if ( int.Parse( nums[i].ToString() ) % 2 == 0 )
    {
        countEven++;
    }
    else
    {
        countOdd++;
    }
}

Console.WriteLine($"{countEven} even numbers \n{countOdd} odd numbers");
Console.ReadKey();

What I do is get each number as aa character in an array char[] and I loop through this array and check if its even or not.

static void Main(string args[]) {
        WriteLine("Please enter a number...");
        var num = ReadLine();

        // Check if input is a number
        if (!long.TryParse(num, out _)) {
            WriteLine("NaN!");
            return;
        }

        var evenChars = 0;
        var oddChars = 0;

        // Convert string to char array, rid of any non-numeric characters (e.g.: -)
        num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
            byte.TryParse(c.ToString(), out var b);
            if (b % 2 == 0)
                evenChars++;
            else
                oddChars++;
        });

        // Continue with code

    }

EDIT: You could also do this with a helper (local) function within the method body:

static void Main(string args[]) {
        WriteLine("Please enter a number...");
        var num = ReadLine();

        // Check if input is a number
        if (!long.TryParse(num, out _)) {
            WriteLine("NaN!");
            return;
        }

        var evenChars = 0;
        var oddChars = 0;

        // Convert string to char array, rid of any non-numeric characters (e.g.: -)
        num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
            byte.TryParse(c.ToString(), out var b);
            if (b % 2 == 0)
                evenChars++;
            else
                oddChars++;

            // Alternative method:
            IsEven(b) ? evenChars++ : oddChars++;
        });

        // Continue with code

        bool IsEven(byte b) => b % 2 == 0;
    }

Why am I using a byte?

Dealing with numbers, it is ideal to use datatypes that don't take up as much RAM. Granted, not as much an issue nowadays with multiple 100s of gigabytes possible, however, it is something not to be neglected. An integer takes up 32 bits (4 bytes) of RAM, whereas a byte takes up a single byte (8 bits).

Imagine you're processing 1 mio. single-digit numbers, and assigning them each to integers. You're using 4 MiB of RAM, whereas the byte would only use up 1 MiB for 1 mio. numbers.

And seeming as a single-digit number (as is used in this case) can only go up to 9 (0-9), you're wasting a potential of 28 bits of memory (2^28) - whereas a byte can only go up to 255 (0-255), you're only wasting a measly four bits (2^4) of memory.

If the Input number is a 32-bit integer (user pick the length of the number) if asked:

  1. The number of even digits in the input number
  2. Product of odd digits in the input number
  3. The sum of all digits of the input number
private void button1_Click(object sender, EventArgs e) {

    int num = ConvertToInt32(textBox1.Text);
    int len_num = textBox1.Text.Length;
    int[] arn = new int[len_num];
    int cEv = 0; pOd = 0; s = 0;

    for (int i = len_num-1; i >= 0; i--) { // loop until integer length is got down to 1
        arn[i] = broj % 10; //using the mod we put the last digit into a declared array
        if (arn[i] % 2 == 0) { // then check, is current digit even or odd  
            cEv++; // count even digits
        } else { // or odd
            if (pOd == 0) pOd++; // avoid product with zero
            pOd *= arn [i]; // and multiply odd digits
        }
        num /= 10; // we divide by 10 until it's length is get to 1(len_num-1)
        s += arn [i]; // sum of all digits 
    }
    // and at last showing it in labels...
    label2.Text = "a) The even digits count is: " + Convert.ToString(cEv);
    label3.Text = "b) The product of odd digits is: " + Convert.ToString(pOd);
    label4.Text = "c) The sum of all digits in this number is: " + Convert.ToString(s);
}

All we need in the interface is the textbox for entering the number, the button for the tasks, and labels to show obtained results. Of course, we have the same result if we use a classic form for the for loop like for (int i = 0; and <= len_num-1; i++) - because the essence is to count the even or odd digits rather than the sequence of the digits entry into the array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM