对“一道有趣的题目”的解答

前段时间Max Gan发布了一篇名为一道有趣的题目的文章,由于Max Gan个人博客的问题,没有能把源码贴上去,深感遗憾。

现把原题和我的解答贴在这里。

题目描述

原题链接:一道有趣的题目

请用您熟悉的语言编写一个函数,该函数只有一个参数n(取值范围为1-9)。假设n为3时,输出如下内容:
            3
           323
          32123
         3210123
          32123
           323
            3

求最优解决代码,不是海量计算,代码越少超好!!

解题分析

这是类似于打印杨辉三角的题。

由于输出的菱形下半部分和上半部分完全一样,因此可以使用缓存输出的方式减少代码和运行时间。

注意到输入n取值范围为1-9,而long的最大值超过9位,因此可以用两个long来拼接处要输出的一行数字,这样可以减少两个for循环,当然,计算方式需要一定技巧。

无论从运行速度上还是代码行数上都比较优秀,唯一的缺点就是只能支持输入不超过9的。另外,在原题地址处看到一个javascript的解答,可惜由于Max Gan博客帖回复的时候会进行一定的过滤,导致无法看到解答。希望能够看到更加短小精彩的解决方案~

我的解答

#include <stdio.h>

void solution(int n)
{
	char outputCache[10][20];
	long value = n, sum = n * 2, p = 11;
	printf("%*d\n", n + 1, value);
	for(int i=1; i<=n; i++)
	{
		long anothervalue = sum - value;
		printf("%*ld%d%ld\n", n, value, n - i, anothervalue);
		sprintf(outputCache[i - 1], "%*ld%d%ld\n", n, value, n - i, anothervalue);
		value = value * 10 + n - i;
		sum = (2 * n - i) * p;
		p = p * 10 + 1;
	}
	for(int i=n - 1; i>=0; i--)
		printf("%s", outputCache[i]);
	printf("%*d\n", n + 1, n);
}

int main()
{
	int n;
	scanf("%d", &n);
	solution(n);
	return 0;
}
posted @ 2010-07-15 15:10  HCOONa  阅读(288)  评论(0编辑  收藏  举报