SequenceSum
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.
ncan 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的更多相关文章
- 庞果英雄会第二届在线编程大赛·线上初赛:AB数
题目链接 给定两个正整数a,b,分别定义两个集合L和R, 集合L:即把1~a,1~b中整数乘积的集合定义为L = {x * y | x,y是整数且1 <= x <=a , 1 <= ...
随机推荐
- spring heibernate 调用存储过程
一:参考网址 http://sunbin123.iteye.com/blog/1007556 二:示例 @Autowired @Qualifier("jdbcTemplate") ...
- [SQL Server]树形结构的创建
对于SQL Server来说,构建显示一个树形结构不是一件容易的事情,逻辑构造能力不是它的强项.不过也不是说它没有能力干这个事情,只要换一种思维方式就可以理解它的工作原理. 例如,现在有一张表的内容如 ...
- phpcmsV9中表单向导在js调用里日期控件在IE下报Calendar未定义的解决办法
最近在phpcmsV9里用表单向导弄个的提交表单,但用了日期和时间类型时,用 <script language='javascript' src='{APP_PATH}index.php?m ...
- Microsoft Office Excel 不能访问文件
问题描述: Microsoft Office Excel 不能访问文件“XX.xls”.可能的原因有: 1 文件名称或路径不存在.2 文件正被其他程序使用.3 您正要保存的工作簿与当前打开的工作簿同名 ...
- linux工作队列
工作队列一般用来做滞后的工作,比如在中断里面要做很多事,但是比较耗时,这时就可以把耗时的工作放到工作队列.说白了就是系统延时调度的一个自定义函数. 工作队列是实现延迟的新机制,从 2.5 版本 Lin ...
- SpringJUnit4加载类目录下(src)和WEF-INF目录下的配置文件
路径说明: 一.加载类目录下的配置文件 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:ap ...
- WPF 视图分组排序
视图分组排序 效果: 实现步骤: 第一步:为分组做一个标题头,就是效果图中的浅蓝色部分: <DataGrid.GroupStyle>标签部分: <DataGrid x:Name=&q ...
- uva 125
floyd 算法 如果存在无数条路 则存在a->a的路 a->b的路径数等于 a->i 和 i->b(0=<i<=_max) 路径数的乘积和 #includ ...
- CodeForces 32C
额 找找规律吧 要用long long 才过. #include <cstdio> #include <algorithm> using namespace std; in ...
- hdu 4403
水水的dfs #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath& ...