SequenceSum

Sum of 'n' Numbers

sum_of_n (or SequenceSum.sumOfN in Java, SequenceSum.SumOfN in C#) takes an integer n and returns aList (an Array in Java/C#) of length abs(n) + 1. The List/Array contains the numbers in the arithmetic series produced by taking the sum of the consecutive integer numbers from 0 to n inclusive.

  • n can also be 0 or a negative value.

Example:

5 -> [0, 1, 3, 6, 10, 15]

-5 -> [0, -1, -3, -6, -10, -15]

7 -> [0, 1, 3, 6, 10, 15, 21, 28]

Linq的无形装逼太过致命了

public class SequenceSum
{
public static int[] SumOfN(int n)
{
//TODO: Write your solution here
return Enumerable.Range(, Math.Abs(n) + ).Select(item => Enumerable.Range(, item).Aggregate(, (x, y) => x + y)).Select(item => (n >= ) ? item : -item).ToArray();
}
}

需要注意的是,Enumerable.Range中第一个参数是起始数字,第二个参数是序列总个数Enumerable.Range(5,4)  结果是5,6,7,8

其他人的解法:

using System.Linq;

public class SequenceSum
{
public static int[] SumOfN(int n)
{
return Enumerable.Range(, n + ).Select(x => x * (x + ) / ).ToArray();
}
}

SequenceSum的更多相关文章

  1. 庞果英雄会第二届在线编程大赛·线上初赛:AB数

    题目链接 给定两个正整数a,b,分别定义两个集合L和R, 集合L:即把1~a,1~b中整数乘积的集合定义为L = {x * y | x,y是整数且1 <= x <=a , 1 <= ...

随机推荐

  1. 为 Web 设计师准备的 25+ 款扁平 UI 工具包

    Flat UI Kit by Riki Tanone (free) Flat UI Kit (PSD) by Devin Schulz (free) Eerste UI Kit (free) Metr ...

  2. 转 IHttpModule不起作用

    在 Visual Studio 中,测试 IHttpModule(httpModules) 正常,但是放到服务器上去就不起作用了,这多半得多服务器 IIS 配置入手. 一.看“应用程序池”的“托管管道 ...

  3. Django设置

    运行 django-admin.py startproject [project-name] 命令会生成一系列文件,在Django 1.6版本以后的 settings.py 文件中有以下语句: # B ...

  4. Thinkphp3.2.2的上传问题

    学习了Thinkphp3.2.2的上传,报出了FILE: F:\development\yxk\Cord\Library\Think\Upload.class.php LINE: 257错误 这应该是 ...

  5. install ruby and ruby gem

    sudo apt-get install ruby #find an folder and: git clone https://github.com/rubygems/rubygems.git cd ...

  6. 解决ora-01652无法通过128(在表空间temp中)扩展temp段

    问题描述: 今天建索引的时候报:ora-01652无法通过128(在表空间temp中)扩展temp段 1.查看表空间是自动增长,且建表空间时是没有设表空间最大值的. 2.查看了一下表空间剩余多少竟然只 ...

  7. Matlab删除NaN数据

    删除包含NaN的行: a(any(isnan(a), 2),:) = []; 删除全部为NaN的行: a(all(isnan(a), 2),:) = [];

  8. HelloWorld和数据绑定

    HelloWorld和数据绑定 目录导读: AngularJS 系列 学习笔记 目录篇 前言: 好记性不如烂键盘,随笔就是随手笔记,希望以后有用. 本篇目录: 1. Hello World 2. An ...

  9. 【莫比乌斯反演】关于Mobius反演与lcm的一些关系与问题简化(BZOJ 2154 crash的数字表格&&BZOJ 2693 jzptab)

    BZOJ 2154 crash的数字表格 Description 今天的数学课上,Crash小朋友学习了最小公倍数(Least Common Multiple).对于两个正整数a和b,LCM(a, b ...

  10. c#带参数和返回值的函数 开启线程调用的方法

    public delegate string DgTest(); private void btn_District_Click(object sender, EventArgs e) { //实例化 ...