一同事去面试:
1+2-3+4-5……+n
用最高效的方法实现
大家各抒己见

解决方案 »

  1.   

    数列求通项式,高一数学题目...这种题不是考编程语言而是考数学知识和逻辑思维,用递归或循环都是很愚蠢的做法...下面的代码如果看不懂就应该回去找你的高中数学老师重修高中数学,并且很大可能你不适合干这行...int fun(int n){
    switch(n){
    case 1:
    return 1;
    case 2:
    return 3;
    default:
    if(n<1)
    throw new ArgumentException();
    if(n%2==0){
    return n/2+2;
    }else{
    return 1-n/2;
    }
    }
    }
      

  2.   


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("请输入n的大小:");
                int n = Convert.ToInt32(Console.ReadLine());
                int sum = (1 + n) / 2 * n;       //求和公式
                Console.WriteLine("1加到n总和为:{0}",sum);
            }
        }
    }