# Count even and odd digits in an Integer

Last Updated : 16 Feb, 2023

A certain number is given and the task is to count even digits and odd digits of the number and also even digits are present even a number of times and, similarly, for odd numbers.

```Print Yes If:
If number contains even digits even number of time
Odd digits odd number of times
Else
Print No```

Examples :

```Input : 22233
Output : NO
count_even_digits = 3
count_odd_digits = 2
In this number even digits occur odd number of times and odd
digits occur even number of times so its print NO.

Input : 44555
Output : YES
count_even_digits = 2
count_odd_digits = 3
In this number even digits occur even number of times and odd
digits occur odd number of times so its print YES.```

Efficient solution for calculating even and odd digits in a number.

## C++

 `// C++ program to count  ` `// even and odd digits  ` `// in a given number ` `#include ` `using` `namespace` `std; ` ` `  `// Function to count digits ` `int` `countEvenOdd(``int` `n) ` `{ ` `      ``// Initialize event_count and odd_count ` `    ``int` `even_count = 0; ` `    ``int` `odd_count = 0; ` `       `  `    ``while` `(n > 0)  ` `    ``{ ` `        ``int` `rem = n % 10; ` `          ``// if condition is true then increment even_count ` `        ``if` `(rem % 2 == 0) { ` `            ``even_count++; ` `        ``} ` `          ``// increment odd_count ` `        ``else` `{ ` `            ``odd_count++; ` `        ``} ` `        ``n = n / 10; ` `    ``} ` `    ``cout << ``"Even count : "`  `         ``<< even_count; ` `    ``cout << ``"\nOdd count : "` `         ``<< odd_count; ` `    ``if` `(even_count % 2 == 0 && odd_count % 2 != 0) { ` `        ``return` `1; ` `    ``} ` `    ``else` `{ ` `        ``return` `0; ` `    ``} ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``int` `n; ` `    ``n = 2335453; ` `      ``// Function call ` `    ``int` `t = countEvenOdd(n); ` `    ``if` `(t == 1){ ` `        ``cout << ``"\nYES"` `<< endl; ` `    ``} ` `    ``else``{ ` `        ``cout << ``"\nNO"` `<< endl; ` `    ``} ` `    ``return` `0; ` `} `

## Javascript

Output

```Even count : 2
Odd count : 5
YES```

Time Complexity: O(n)

Auxiliary Space: O(1)

Another solution to solve this problem is a character array or string.

## Javascript

Output

```Even count : 1
Odd count : 2
NO```

Time Complexity: O(n)

Auxiliary Space: O(1)

#### Method #3:Using typecasting(Simplified Approach):

• We have to convert the given number to a string by taking a new variable.
• Traverse the string, convert each element to an integer.
• If the character(digit) is even, then the increased count
• Else increment the odd count.
• If the even count is even and the odd count is odd, then print Yes.
• Else print no.

Below is the implementation of the above approach:

## Javascript

 ` `

Output

`Yes`

Time Complexity: O(n)

Auxiliary Space: O(1)

Previous
Next