标签:blog io ar os 使用 sp for 2014 log
题目1506:求1+2+3+...+n 时间限制:1 秒内存限制:128 兆特殊判题:否提交:1261解决:723 题目描述: 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 输入: 输入可能包含多个测试样例。 对于每个测试案例,输入为一个整数n(1<= n<=100000)。 输出: 对应每个测试案例, 输出1+2+3+…+n的值。 样例输入: 3 5 样例输出: 6 15
解法1:使用构造函数模拟循环
#include <iostream>
#include<stdio.h>
using namespace std;
class Temp{
public :
    Temp(){
        N++;
        Sum+=N;
    }
    static void reset(){
        N=0;
        Sum=0;
    }
    static unsigned int getSum(){
        return Sum;
    }
private :
    static unsigned int N;
    static unsigned int Sum;
};
unsigned int Temp::N = 0;
unsigned int Temp::Sum = 0;
unsigned int sum(int n){
    Temp::reset();
    Temp::reset();
    Temp*a = new Temp[n];
    //delete[] a;
    //a = NULL;
    return Temp::getSum();
}
int main()
{
   int n;
   while(scanf("%d",&n)!=EOF){
    printf("%d\n",sum(n));
   }
    return 0;
}#include <iostream>
#include<stdio.h>
using namespace std;
class A;
A* array[2];
class A{
public:
    virtual unsigned int sum(unsigned int n){
        return 0;
    }
};
class B:public A{
public:
    virtual unsigned int sum(unsigned int n){
        return array[!!n]->sum(n-1)+n;
    }
};
int sum(int n){
    A a;
    B b;
    array[0] = &a;
    array[1] = &b;
    int value = array[1]->sum(n);
    return value;
}
int main()
{
   int n;
   while(scanf("%d",&n)!=EOF){
    printf("%d\n",sum(n));
   }
    return 0;
}
解法3:使用函数指针
#include <iostream>
#include<stdio.h>
using namespace std;
typedef unsigned int (*fun)(unsigned int);
unsigned int teminator(unsigned int n){
    return 0;
}
unsigned int sum(unsigned int n){
    static fun f[2] = {teminator,sum};
    return n+f[!!n](n-1);
}
int main()
{
   int n;
   while(scanf("%d",&n)!=EOF){
    printf("%d\n",sum(n));
   }
    return 0;
}
标签:blog io ar os 使用 sp for 2014 log
原文地址:http://blog.csdn.net/hackcoder/article/details/41893841