4000000000内满足f(n)=n最大的n(f(n)统计0~n中所有1的个数)

#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <cstdio>
using namespace std;

int gTable[10];
const unsigned int gMAX = 4000000000L;

int f(int n) {
	int ret = 0;
	int ntemp = n;
	int ntemp2 = 1;
	int i = 1;
	while(ntemp) {
		ret += ((ntemp-1)/10+1) * i;
		if((ntemp%10) == 1) {
			ret -= i;
			ret += ntemp2;
		}
		ntemp = ntemp/10;
		i*=10;
		ntemp2 = n%i + 1;
	}
	return ret;
}

int count1(int n) {
	int count = 0;
	while(n) {
		if(n%10 == 1)
			++count;
		n /= 10;
	}

	return count;
}

int cal(unsigned int number, int nwei, int count1, unsigned int ncount) {
	int i, n = 1;
	unsigned int maxcount;
	if(nwei == 0) {
		ncount += count1;
		if(number == ncount) {
			printf("f(%d)=%d\n", number, number);
		}
		return ncount;
	}
	for(i=0; i<nwei; ++i)
		n *= 10;
	maxcount = ncount + gTable[nwei-1];
	maxcount += count1*n;
	if(ncount > (number + (n-1))) {
		return maxcount;
	}
	if(maxcount < number)
		return maxcount;
	n /= 10;
	for(i=0; i<10; ++i) {
		if(i==1)
			ncount = cal(number+i*n, nwei-1, count1+1, ncount);
		else
			ncount = cal(number+i*n, nwei-1, count1, ncount);
	}
	return ncount;
}

int main() {
	int i;
	unsigned int n=1;
	unsigned int ncount = 0;
	int nwei = 0;
	int ncount1;

	//init gTable
	for(i=0; i<10; ++i) {
		n *= 10;
		gTable[i] = f(n-1);
		cout << "gTable[" << i << "] : f(" << n-1 << ") : " << gTable[i] << endl;
	}

	n=0;
	nwei = 0;
	ncount1 = 0;
	while(n<gMAX) {
		unsigned int temp;
		temp = 1;
		ncount = cal(n, nwei, ncount1, ncount);
		for(i=0; i<nwei; ++i) {
			temp *= 10;
		}
		n += temp;
		if(n/temp/10 == 1)
			++nwei;
		ncount1 = count1(n);
	}

	printf("ncount1:%d, ncount:%d, nwei:%d\n", ncount1, ncount, nwei);
	return 0;
}



转载于:https://my.oschina.net/ITHaozi/blog/287251

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值