1.最简单的办法就是用递归来实现。以生成由4,7,9三个数组成,且不超过MAX_NUMBER、不小于MIN_NUMBER的数的个数:

int number(long x)
{
if(x > MAX_NUMBER)
return 0;
if(x > MIN_NUMBER)
cout << x << endl;
return number(x*10 + 4) + number(x*10 + 7) + number(x*10 + 9) + (x >= MIN_NUMBER ? 1 : 0);
}
number()返回值是符合条件的数的个数。
用此种方法比较通用,解SRM_403_DIV1_250最为简单。
2.因题中仅要求2个数,因此可以用2进制位构造出所有由这两个数组成的数。
1
for( int k = 1; k <=9; k++ )
{
2
for( int i = 0; i < 1 << k; i++ )
{
3
vec.clear();
4
// generate the lucky number
5
for(int j = 1, index = 0; index < len; j <<= 1, index++)
{
6
if( (j & i) == 0 )
7
vec.push_back('4');
8
else
9
vec.push_back('7');
10
}
11
vec.push_back('\0');
12
int num = atoi(&vec[0]);
13
if( a <= num && num <= b )
14
count++;
15
}
16
}
其中,k是用来控制每次生成的数的长度的,最多不超过9。
3. 划分成多个区间
如果a和b长度相同,则仅需要双重循环i和j即可。
如果不相同,则只需要计算区间(a, maxnumber of length(a)) + (minnumber of length(b), b) + 长度处于[length(a)+1,length(b)-1]之间的数的个数。后一部分的算法为
count = 1 << length; length属于[length(a)+1,length(b)-1]

附原题(From TopCoder)

/**//*
Problem Statement
John thinks 4 and 7 are lucky digits, and all other digits are not lucky. A lucky number is a number that contains only lucky digits in decimal notation.
You are given ints a and b. Return the number of lucky numbers between a and b, inclusive.
Definition
Class:
TheLuckyNumbers
Method:
count
Parameters:
int, int
Returns:
int
Method signature:
int count(int a, int b)
(be sure your method is public)

Constraints
-
a will be between 1 and 1,000,000,000, inclusive.
-
b will be between a and 1,000,000,000, inclusive.
Examples
0)

1
10
Returns: 2
There are only two lucky numbers among the first ten positive integers.
1)

11
20
Returns: 0
But there are none among the next ten.
2)

74
77
Returns: 2
These two numbers are lucky. There are no additional lucky numbers between them.
3)

1000000
5000000
Returns: 64

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
*/