Calculating Specific Digit Occurrences in Integers
Algorithm Logic
The task requires implementing a function that calculates the frequency of a specific digit (0-9) within a given integer. The primary challenge involves handling the sign of the input number and the edge case where the input is zero.
Since the input integer is passed as a const int, it cannot be modified directly. Therefore, a local variable is used to work with the absolute value of the number. A standard loop iterates through the digits by using the modulo operator to extract the least significant digit and integer division to reduce the number.
Edge Case Handling
A specific condition arises when the input integer is 0 and the target digit is also 0. In this scenario, the loop condition typically used for positive integers would fail to execute, returning 0 instead of 1. An explicit check is required to return 1 in this instance.
Implementation 1: Direct Iteration
int countDigitOccurrences(const int number, const int target) {
long currentVal = number;
if (currentVal < 0) {
currentVal = -currentVal;
}
if (target == 0 && number == 0) {
return 1;
}
int frequency = 0;
while (currentVal > 0) {
int digit = currentVal % 10;
if (digit == target) {
frequency++;
}
currentVal /= 10;
}
return frequency;
}Implementation 2: Histogram Approach
An alternative strategy involves utilizing an array of size 10 to record the count of every digit (0-9) present in the number. This allows for O(1) lookup after the iteration completes.
int countDigitHistogram(const int number, const int target) {
int absoluteVal = (number < 0) ? -number : number;
int buckets[10] = {0};
if (absoluteVal == 0) {
buckets[0] = 1;
} else {
while (absoluteVal > 0) {
int digit = absoluteVal % 10;
buckets[digit]++;
absoluteVal /= 10;
}
}
return buckets[target];
}