首页
社区
课程
招聘
[原创]第一题
发表于: 2008-11-28 13:31 7129

[原创]第一题

2008-11-28 13:31
7129
很多题看不明白,还是先从第一题开始吧
我得计算过程是从0开始的到输入的数的统计,即[0, ?x]
比如 输入15
输出
[0]2        [1]8        [2]2        [3]2        [4]2        [5]2        [6]1        [7]1        [8]1        [9]1

欢迎大家指正

// DigitCount.cpp : Defines the entry point for the console application.
//

//#include "stdafx.h"

#include <iostream>
#include <fstream>

using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ostream;
using std::ofstream;


//static int digits[10] = {0};

void ShowResult(const int digits[10])
{
	for (int i = 0; i < 10; ++i)
	{
		cout<<'['<<i<<']'<<digits[i]<<'\t';
	}
	cout<<endl;

}



void Test(unsigned value, int digits[10])
{
	// init digits
	memset(digits, 0, sizeof(digits));
	digits[0] = 1;

	unsigned pos = 0, ratio = 1;
	unsigned curDigit = value % 10, head = value / 10, tail = 0;

	//do
	while (head > 0)
	{

		// calculate current digit and '0' digit
		if (curDigit == 0)
		{
			digits[0] += (head - 1) * ratio + (tail + 1);
		}
		else
		{
			digits[0] += head * ratio;
			digits[curDigit] += head * ratio + (tail + 1);
		}

		// calculate y < curDigit
		for (unsigned i = 1; i < curDigit; ++i)
		{
			digits[i] += (head + 1) * ratio;
		}

		// calculate y > curDigit
		for (unsigned i = curDigit + 1; i <= 9; ++i)
		{
			digits[i] += head * ratio;
		}

		// update tail, ratio, curDigit, head
		tail += ratio * curDigit;
		ratio *= 10;
		curDigit = head	% 10;
		head /= 10;
	}

	// for curDigit == 0
	// do noting

	// for 0 < y < curDigit
	for (unsigned i = 1; i < curDigit; ++i)
	{
		digits[i] += ratio;
	}

	// for y = curDigit
	digits[curDigit] += tail + 1;

	// for y > curDigit
	// do nothing

}

void PrintDigits(int digits[10], ostream& os)
{
	for (int i = 0; i < 10; ++i)
	{
		os<<'['<<i<<']'<<digits[i]<<'\t';
	}

	os<<endl;

}

int main(int argc, char* argv[])
{

	int digits[10] = {0};

	const char* INPUTFILE = "in.txt";
	const char* OUTPUTFILE = "out.txt";

	ifstream is(INPUTFILE);
	ofstream os(OUTPUTFILE);
	unsigned value = 0;
	int testCount = 0;
	is>>testCount;
	

	while (--testCount > 0)
	{
		is>>value;
		Test(value, digits);
		//Debug_Test(value, digits);

		PrintDigits(digits, os);
		
		// print result in console
		//PrintDigits(digits, cout);

	}

	os.close();
	is.close();
	
	return 0;
}


[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!

上传的附件:
收藏
免费 0
支持
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回
//