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. AngularJS(8)-指令directive

    AngularJS 提供了很多内置的指令,你可以使用它们来为你的应用添加功能. 诸如这些: 此外,你可以使用模块来为你应用添加自己的指令: 运行结果:

  2. 转发 PHP 资料(一)

    WebShell隐藏思路.webshell磁盘读写动态检测.webshell沙箱动态检测(2)   作为WebShell检测.CMS修复.WebShell攻防研究学习的第二篇文章 本文旨在研究Webs ...

  3. discuz 注册用户用到的几个表

    通过开启记录:mysql记录日志,筛出如下信息: INSERT INTO `userclub`.pre_ucenter_members SET secques='', username='pthlp1 ...

  4. php session的应用举例

    本文原始链接:http://www.jbxue.com/article/9281.html 1,session可以保存任意类型的数据.因为是保存在服务器上的(即已经序列化). 2,session运行机 ...

  5. 《疯狂的android讲义第3版》读书笔记

    第一章.开始启程,你的第一行android代码 1.android系统架构: 1)linux内核层:为底层硬件提供驱动,如显示驱动.音频驱动.照相机驱动.蓝牙驱动.Wifi驱动.电源管理等 2)系统运 ...

  6. (转载)总结一下SQL语句中引号(')、quotedstr()、('')、format()在SQL语句中的用法

    总结一下SQL语句中引号(').quotedstr().('').format()在SQL语句中的用法 总结一下SQL语句中引号(').quotedstr().('').format()在SQL语句中 ...

  7. Spark小课堂Week1 Hello Spark

    Spark小课堂Week1 Hello Spark 看到Spark这个词,你的第一印象是什么? 这是一朵"火花",官方的定义是Spark是一个高速的.通用的.分布式计算系统!!! ...

  8. onclick控制元素显示与隐藏时,点击第一次无反应的原因

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  9. Path of Equal Weight (DFS)

    Path of Equal Weight (DFS)   Given a non-empty tree with root R, and with weight Wi assigned to each ...

  10. mysql 的 存储结构(储存引擎)

    1 MyISAM:这种引擎是mysql最早提供的.这种引擎又可以分为静态MyISAM.动态MyISAM 和压缩MyISAM三种:    静态MyISAM:如果数据表中的各数据列的长度都是预先固定好的, ...