一道面试题:求1+2+…+n,不使用乘除法、for、while、if 、else、switch、case 等关键字

来源:互联网 发布:java线程 终止 编辑:程序博客网 时间:2024/04/27 17:38
题目:求1+2+…+n,

要求不能使用乘除法、for、while、if 、else、switch、case 等关键字以及条件判断语句(A?B:C)


下面提出三种方式方法用C++实现:

#include <iostream>using namespace std;//通过逻辑运算符的短路来处理int Calc1(int n){    int value = 0;    return n < 0 || (value = n + Calc1(n - 1)), value;}//通过除0异常来处理,需要在编译命令行中启用/EHa(启用C++异常,但有SEH异常)//gcc下不知道什么情况,未测试int Calc2(int n){    try    {        return n % n + n + Calc2(n - 1);    }    catch (...)    {        return 0;    }}//通过n>0作为数组的索引来处理void Calc3_Last(int sum, int value, int *result){    *result = sum;}void Calc3_Body(int sum, int value, int *result){    void (*func[])(int, int, int *) = {Calc3_Last, Calc3_Body};    func[value > 0](sum + value, value - 1, result);}int Calc3(int n){    int result;    Calc3_Body(0, n, &result);    return result;}//主函数int main(){    cout<<Calc1(100)<<endl;    cout<<Calc2(100)<<endl;    cout<<Calc3(100)<<endl;    return 0;}

C#不支持逗号表达式,不能用上面的第一种方法:

using System;namespace Slx.TestSumN_cs{    static class Program    {        //利用除0异常来处理        public static int Calc2(int n)        {            try            {                return n % n + n + Calc2(n - 1);            }            catch (System.Exception)            {                return 0;            }        }        //通过n>0作为数组的索引来处理        public delegate void Calc3Delegate(int sum, int n, ref int result);        public static void Calc3_Last(int sum, int n, ref int result)        {            result = sum;        }        public static void Calc3_Body(int sum, int n, ref int result)        {            Calc3Delegate[] bodys = {Calc3_Last, Calc3_Body};            bodys[Convert.ToInt32(n > 0)](sum + n, n - 1, ref result);        }        public static int Calc3(int n)        {            int result = 0;            Calc3_Body(0, n, ref result);            return result;        }        //主函数        public static void Main(string[] args)        {            Console.WriteLine(Calc2(100));            Console.WriteLine(Calc3(100));        }    }}

原创粉丝点击