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

1 篇文章 0 订阅
题目:求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));
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值