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. linux与windows共享剪贴板(clipboard)

    linux与windows共享剪贴板(clipboard)的方法 先说两句废话,其实linux和windows之间不需要共享剪贴板,直接在putty中,按住SHIFT+鼠标选择就可以了. 但是作为一种 ...

  2. Discuz x2.5 单页制作的教程

    首先,单页包括该单页的php文件和该单页的模板(.htm)文件,比如:host.php.host.htm 单页的php文件内容如下: <?php require './source/class/ ...

  3. select&pselect/poll&ppoll/epoll

    select/pselect, poll和epoll的区别 select,epoll,poll比较 select,poll,epoll进化 Handling of asynchronous event ...

  4. iOS中touches事件,addtarget ...action和GestureRecognizer详解

    刚学完uiview,uicontrol类,许多人知道 touchesBegain,touchesMoved,touchesEnd,GestureRecognizer的用途,但仔细考虑这些事件之间的关系 ...

  5. Redis之七种武器

    长生剑.孔雀翎.碧玉刀.多情环.离别钩.霸王枪.拳头是古龙笔下的七种武器,而本文打算将Redis的几种使用方式 Strings.Hashs.Lists.Sets.Sorted Sets.Pub/Sub ...

  6. SQL优化之索引

    最近碰到一个问题,因数据量越来越大,然后存储过程查询过慢!后来发现没有加索引列导致的!从这里让我开始慢慢去了解索引的原理及作用!以下是我的总结,个人理解只供参考: SQL SERVER提供了两种索引: ...

  7. Matlab划分测试集和训练集

    % x是原数据集,分出训练样本和测试样本 [ndata, D] = size(X); %ndata样本数,D维数 R = randperm(ndata); %1到n这些数随机打乱得到的一个随机数字序列 ...

  8. <base target="_blank"/>

    <base target=_blank> 是将基本链接的目标框架都改为新页打开

  9. PAT-乙级-1016. 部分A+B (15)

    1016. 部分A+B (15) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 正整数A的“DA(为1位整数)部 ...

  10. Clojure语法学习-循环

    do和块语句 在Scala中,花括号{}括起来的语句构成一个block,它的值就是最后一个语句的值. scala> val a = { | println("a") | 1} ...