codewars解题笔记---Grasshopper - Summation

题目

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

For example:

summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8

解析

编写一个程序,查找从1到num的每个数字的总和。该数字始终是大于0的正整数。

我的答案

public static int summation(int n) {

        return IntStream.rangeClosed(1,n).sum();
    }

最优答案

 public static int summation(int n) {

        return  n*(n+1)/2;
    }
扫描二维码关注公众号,回复: 5035666 查看本文章

猜你喜欢

转载自blog.csdn.net/z_victoria123/article/details/86604295
今日推荐