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++
#include <iostream>
using namespace std;
int countEvenOdd( int n)
{
int even_count = 0;
int odd_count = 0;
while (n > 0)
{
int rem = n % 10;
if (rem % 2 == 0) {
even_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;
}
}
int main()
{
int n;
n = 2335453;
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>
function getResult(n)
{
var st = n.toString();
var even_count = 0;
var odd_count = 0;
for ( var i = 0; i < st.length; i++)
{
if ((st.charAt(i) % 2) == 0)
even_count += 1;
else
odd_count += 1;
}
if (even_count % 2 == 0 &&
odd_count % 2 != 0)
return "Yes" ;
else
return "no" ;
}
var n = 77788;
document.write(getResult(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...