1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
#include <algorithm>
using namespace std;
//======================================================================
int numdigits( int n, int &power )
{
int ndigits = 1;
power = 1;
int p = 10;
while ( n >= p )
{
ndigits++;
power = p;
p *= 10;
}
return ndigits;
}
//======================================================================
int cumulative( int target, int n, int ndigits = -1, int power = 1 )
{
bool start = ndigits < 0;
if ( start ) ndigits = numdigits( n, power );
int first = n / power;
if ( ndigits == 1 ) return ( n >= target );
int freq;
if ( target == 0 && start )
{
freq = max( first - 1, 0 ) * ( ndigits - 1 ) * power / 10
+ cumulative( target, n % power, ndigits - 1, power / 10 )
+ cumulative( target, power - 1, -1, 1 );
}
else
{
// Contributions from other than first digit
freq = first * ( ndigits - 1 ) * power / 10
+ cumulative( target, n % power, ndigits - 1, power / 10 );
// Number of occurrences of target as first digit
if ( first > target ) freq += power;
else if ( first == target ) freq += n % power + 1;
}
return freq;
}
//======================================================================
int main()
{
int a, b, digit;
cout << "Find number of occurrences of specified digit (0-9) between a and b (inclusive), 0 <= a <= b\n";
cout << "Input a, b, digit (separated by spaces): ";
cin >> a >> b >> digit;
cout << "Number of occurrences of " << digit << " in " << a << " <= x <= " << b << " is ";
if ( a <= 0 ) cout << cumulative( digit, b ) << '\n';
else cout << cumulative( digit, b ) - cumulative( digit, a - 1 ) << '\n';
}
|