题解 | #等差数列#

等差数列

http://www.nowcoder.com/practice/f792cb014ed0474fb8f53389e7d9c07f

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int count = 0;
            for (int i = 1; i <= n; i++) {
                int number = 3 * i - 1;
                count += number;
            }
            System.out.println(count);
        }
        sc.close();
    }
}

更优解:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            if (n > 1) {
                int last = 3 * n - 1;
                System.out.println((2 + last) * n / 2);
            } else {
                System.out.println(2);
            }
        }
        sc.close();
    }
}
全部评论

相关推荐

10-22 19:44
门头沟学院 Java
面了100年面试不知...:那我得去剪个头
点赞 评论 收藏
分享
09-17 10:53
四川大学 C++
牛客91242815...:会写标书没有任何卵用,鉴定为横向垃圾导师的受害者
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务