解决微软面试题

// grammer.cpp : 定义控制台应用程序的入口点。
//made by davidsu33
//第12题(语法)微软面试题
//题目:求1+2+…+n,
//要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;

template<unsigned int>
struct acclum;

template<>
struct acclum<0>
{
	enum {value = 0,};
};

template<>
struct acclum<1>
{
	enum {value = 1,};
};

template<unsigned int N>
struct acclum
{
	enum{ value = (N + acclum<N-1>::value),};
};

int _tmain(int argc, _TCHAR* argv[])
{
	int sum = 0;
	for (unsigned i=1; i<=100; ++i)
	{
		sum += i;
	}

	assert(acclum<100>::value == sum);
	assert(acclum<0>::value == 0);

	return 0;
}


你可能感兴趣的:(C++,面试题)