题解 | #等差数列#

等差数列

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();
    }
}
全部评论

相关推荐

渴望wlb的牛油果很...:直说卡第一学历不就行了 非得拐弯抹角
点赞 评论 收藏
分享
黑皮白袜臭脚体育生:还是喜欢你劝退测开时候桀骜不驯的样子,麻烦恢复一下
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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