- 我的代码(如果要加一个模板参数来判断n和last是否相等,会有意想不到的效果):
- #include <iostream>
- using namespace std;
- const int MAX = 2008080808;
- const int IT = 7;
- template<int n, int curr, int last, int base, int weight>
- class A
- {
- enum{it = n/base%10};
- public:
- enum{result = A<n, (it-(it>IT))* weight+((it<IT)?curr:(it==IT?last:base+curr)), last+base*it, base*10, (weight?weight*9+base:1)> :: result};
- };
- template<int n, int curr, int base, int weight>
- class A<n, curr, n, base, weight>
- {
- public:
- enum {result = curr};
- };
- int main(int argc, char* argv[])
- {
- cout << A<MAX+1, 0, 0, 1, 0>:: result << endl;
- return 0;
- }
- 下面的vitin的代码,思路一样,只是方向相反#include <iostream>
- #include <cstdlib>
- using std::cout;
- using std::endl;
- using std::system;
- typedef unsigned __int64 num_type;
- typedef unsigned short digit_type;
- template <num_type base, size_t exp>
- class power
- {
- public:
- static const num_type value = base * power<base, exp-1>::value;
- };
- template <num_type base>
- class power<base, 0>
- {
- public:
- static const num_type value = 1;
- };
- template <num_type num, num_type base, bool bigger = (num >= base)>
- class log_round
- {
- public:
- static const size_t value = log_round<num/base, base>::value + 1;
- };
- template <num_type num, num_type base>
- class log_round< num, base, false>
- {
- public:
- static const size_t value = 0;
- };
- template <num_type num, digit_type digit>
- class count_of_num
- {
- private:
- static const num_type base = 10;
- static const size_t exp = log_round<num, base>::value;
- static const num_type m_digit = num / power<base, exp>::value;
- static const num_type remain = num - m_digit * power<base, exp>::value;
- static const num_type m_digit_count =
- (m_digit > digit) ? (power<base, exp>::value - count_of_num<power<base, exp>::value-1, digit>::value) :
- ((m_digit == digit) ? (remain+1-count_of_num<remain, digit>::value) : 0);
- public:
- // 设 m_digit * (10^exp) <= num < (m_digit+1)*(10^exp)
- // 则总数目包含以下几项
- // 1、m_digit * (1 到 (10^exp-1) 中的数目)
- // 2、1 到 (num - m_digit * (10^exp)) 中的数目
- // 3、最高位为 digit 的次数(去重)
- // 4、... digit == 0 比较复杂,暂不考虑
- static const num_type value =
- m_digit * count_of_num<power<base, exp>::value-1, digit>::value
- + count_of_num<remain, digit>::value
- + m_digit_count;
- };
- template <digit_type digit>
- class count_of_num <0, digit>
- {
- public:
- static const num_type value = 0;
- };
- int main()
- {
- cout << count_of_num< 2008080808, 7 >::value << endl;
- system("pause");
- return 0;
- }
金山招聘题目:编程计算从1到2008080808之间的整数有多少个含有数字7
最新推荐文章于 2016-05-15 14:34:47 发布