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. DTCMS自定义标签,获取所有栏目文章列表TOP,以及文章通用URL

    网站最近更新等地方,发现DTCMS没有获取所有栏目文章列表的标签,只能自己写 思路:获取所有栏目文章列表不难,难点在于linkurl的写法 1.制作获取所有文章列表标签 DTcms.Web.UI\La ...

  2. 关于canvas中的jquery

    关于h5,相比前端的同事们都很了解了吧!h5里面有个canvas,现在用的蛮火.但是canvas里面的代码确实是有点繁多,特别是要对于图形做什么操作的时候...我昨天无意间发现了一个canvas的插件 ...

  3. PHP生成表格

    <?php /* DROP TABLE IF EXISTS `art`; CREATE TABLE `art` ( `id` int(11) NOT NULL AUTO_INCREMENT, ` ...

  4. Android Wear预览版——尝鲜

    前两天Google推出了Android Wear的SDK,稍稍的瞧了一眼,发现这个预览版的功能还是比较简单的,只有一个通知转发的功能,不过就这么一个功能,带来的效果却是Very Good~~ 功能:发 ...

  5. 修复ecshop商品重量BUG小数位增至五位

    如果ECSHOP商品重量录入为1.499千克,数据库存储值为1.499:如果录入1.499克,存储值为1.显然数据保存有误差,虽然在快递运输中,此误差极小可以忽略不计,但从严谨的角度看,这是不合理的. ...

  6. 使用自定义任务审批字段创建 SharePoint 顺序工作流

    http://msdn.microsoft.com/zh-cn/library/hh824675(v=office.14).aspx#odc_sp14_ta_CreatingSPSeqWorkflow ...

  7. 获取局域网ip

    显然不可使用基于request请求的request.getRemoteAddr()这个是获取广域网内的服务器地址,比如我请求百度使用这个方法就可以获取到百度的服务器地址 那么InetAddress的I ...

  8. spring的三种注解管理器

    1.依赖注入的注解解析器 在配置文件中; * xsd xmlns:context="http://www.springframework.org/schema/context" h ...

  9. AFNetworking 简单应用

    最近最学习 AFNetworking ,根据自己所学对 AFNetWorking 一些简单应用做了一下简单封装,主要有 get,post形式获取 xml,json,get 方式获取图片,下载文件,上传 ...

  10. putty连接linux as5 输入密码后连接中断

    putty连接linux as5 输入密码后连接中断 1.修改putty首页的设置,选择“close session on exit” 为 “never”,之后发现输入密码后,“session clo ...