Sum of 'n' Numbers
来源:互联网 发布:盖尔霍华德 软件 编辑:程序博客网 时间:2024/05/19 20:49
Description:
Sum of 'n' Numbers
sum_of_n
(or SequenceSum.sumOfN
in Java) takes an integern
and returns a List
of length abs(n) + 1. The List
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]
My solution:
public class SequenceSum {public static int[] sumOfN(int n) { int flag = n>0? 1:-1; int[] result = new int[Math.abs(n)+1]; for(int i=0;i<Math.abs(n)+1;i++){ result[i] = i==0? 0:result[i-1]+i*flag; } return result; }}
The best solution I think:
import java.util.stream.IntStream;public class SequenceSum { public static int[] sumOfN(int n) { int modifier = n < 0 ? -1 : 1; int[] range = new int[Math.abs(n) + 1]; IntStream.rangeClosed(0, Math.abs(n)).forEach( i -> {range[i] = i == 0 ? 0 : range[i - 1] + i * modifier;} ); return range; }}
0 0
- Sum of 'n' Numbers
- Sum of numbers from 0 to N -- 7 kyu
- Number of sets of natural numbers less than n which sum to n.
- Sum of Numbers
- Sum of Square Numbers
- Sum of Triangular Numbers
- Sum of Consecutive Prime Numbers
- Sum of Consecutive Prime Numbers
- Sum of Consecutive Prime Numbers
- 1120. Sum of Sequential Numbers
- sum of all integer numbers
- sum of all integer numbers
- Sum of Consecutive Prime Numbers
- Sum of Consecutive Prime Numbers
- Sum of Consecutive Prime Numbers
- Sum of Consecutive Prime Numbers
- The sum of prime numbers
- 633. Sum of Square Numbers
- atol和strtol的区别
- XcodeDebug---闪退调试
- 基本编程元素用到的技巧
- 正则表达式30分钟入门教程
- Android开发之图片处理专题(二):利用AsyncTask和回调接口实现图片的异步加载和压缩
- Sum of 'n' Numbers
- 信道复用技术
- 【连通图|强连通+缩点】POJ-2553 The Bottom of a Graph
- spring-mvc(一)spring-mvc原理小结
- C#调试sqlife几个问题记录
- [暖手][学习阶段-各路杂题][HDU-1157]Who's in the Middle
- 黑马程序员Android第55期——JSP 实例二
- 【BZOJ 1093】 [ZJOI2007]最大半连通子图
- 递归与迭代的区别