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.
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的更多相关文章
- 庞果英雄会第二届在线编程大赛·线上初赛:AB数
题目链接 给定两个正整数a,b,分别定义两个集合L和R, 集合L:即把1~a,1~b中整数乘积的集合定义为L = {x * y | x,y是整数且1 <= x <=a , 1 <= ...
随机推荐
- This bison version is not supported for regeneration of the Zend/PHP parsers
在 mac 中编译 php-src.git 报错: configure: WARNING: This bison version is not supported , excluded: ). con ...
- 【原】隐藏ultraGrid1指定列
void uGrdAllFlight_InitializeRow(object sender, InitializeRowEventArgs e) { /***********TEST START** ...
- window.onbeforeunload 如果取消, 那么javascript变量会保存
function confirmQuit1() { if (ischanged) return 'it is changed !! '; else return 'no change .. '; } ...
- Review PHP设计模式之——单例模式
单例模式: class Single { private static $_instance; private function __construct(){ //define method as p ...
- Delphi Variant oleVariant
The OleVariant type exists on both the Windows and Linux platforms. The main difference between Vari ...
- Virtual Box中 CentOS双网卡设置
Virtual Box中 CentOS双网卡设置: 在Virtual Box中安装CentOS x86-64 6.4(final),配置了双网卡,eth0 为桥接模式 , eth1为内网模式 ...
- Beaglebone Back学习五(PWM测试)
PWM测试 参考链接 1 Enable PWM on BeagleBone with Device Tree overlays 2Using PWM on the Beaglebone Black 3 ...
- IOS成长之路-调用照相机和相册功能(转)
转载自:http://blog.csdn.net/like7xiaoben/article/details/8465237 //先设定sourceType为相机,然后判断相机是否可用(ipod)没相机 ...
- iOS sqlite数据库实现(转)
转载自:http://www.cnblogs.com/macroxu-1982/archive/2012/10/01/2709960.html 1 实现过程添加libsqlite3组件 选择项目后,在 ...
- Python拷贝及多进程与类的问题
最近写python写的尤其不顺利,更多的debug,逐渐的深入,产出却比较少.应该是个瓶颈期,坚持坚持,厚着脸皮也要坚持下去. 0x00 拷贝问题 程序中涉及到多进程和协程,大致的模型是开了2+个进程 ...