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 <iostream> 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;
} |
Java
Python3
C#
PHP
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.
C++
Java
Python3
C#
PHP
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:
C++
Java
Python3
C#
Javascript
<script> // Javascript implementation of above approach function getResult(n)
{ // Converting integer to String
var st = n.toString();
var even_count = 0;
var odd_count = 0;
// Looping till length of String
for ( var i = 0; i < st.length; i++)
{
if ((st.charAt(i) % 2) == 0)
// Digit is even so increment even count
even_count += 1;
else
odd_count += 1;
}
// Checking even count is even and
// odd count is odd
if (even_count % 2 == 0 &&
odd_count % 2 != 0)
return "Yes" ;
else
return "no" ;
} // Driver Code var n = 77788;
// Passing this number to get result function
document.write(getResult(n));
</script> |
Output
Yes
Time Complexity: O(n)
Auxiliary Space: O(1)