Problem Statement
You are given an integer n. You need to return the number of odd digits present in the number.
The number will have no leading zeroes, except when the number is 0 itself.
Examples
Example 1:
Input: n = 7
Output: 1
Explanation: 7 is an odd digit
Example 2:
Input: n = 15
Output: 2
Explanation: Both the digits 1 and 5 are odd.
Approaches
1️⃣ Modulus and Division
Intuition:
To count the number of odd digits in a number, the idea is to extract each digit from the number and check if it is odd. If it is, we increment a counter. This process continues until all digits have been checked.
Steps:
- Initialize a counter to zero for keeping track of the odd digits.
- Extract the last digit of the number using the modulus operator (
n % 10
). - Check if the digit is odd by checking if the digit modulus 2 is not zero (
digit % 2 != 0
). - Increment the counter if the digit is odd.
- Remove the last digit from the number by dividing it by 10 (
n = n / 10
). - Repeat steps 2-5 until the number becomes zero.
- The value of the counter at the end will be the number of odd digits.
Code:
#include <iostream>
int countOddDigits(int n) {
int count = 0;
while (n > 0) {
int digit = n % 10; // Extract the last digit
if (digit % 2 != 0) { // Check if the digit is odd
count++;
}
n = n / 10; // Remove the last digit
}
return count;
}
int main() {
int n;
std::cout << "Enter a number: ";
std::cin >> n;
int result = countOddDigits(n);
std::cout << "Number of odd digits: " << result << std::endl;
return 0;
}
Complexity Analysis:
- Time Complexity:
O(log10(N))
– In every iteration we are dividingN
by 10 (equivalent to the number of digits inN
). - Space Complexity:
O(1)
– Using only couple of variables i.e., constant space.