GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — zc/newcoder/codinginterviews/Sum_Solution.java at master · codeaike/zc

Expand file tree

/

Sum_Solution.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
39 lines (32 loc) · 875 Bytes
/

Sum_Solution.java

Copy path

File metadata and controls

39 lines (32 loc) · 875 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.codinginterviews.array;
/**
* 题目:
* 求1+2+3+...+n -- newcoder 剑指Offer 47
*
*
* 题目描述:
* 求1+2+3+...+n,要求不能使用乘除法、
* for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
*
*/
public class Sum_Solution {
/**
* 思路:
* 1、利用 && 的短路特性实现递归,n<=0时,不运行后面的语句
*/
public int sum_Solution(int n) {
int sum = n;
boolean flag = (n > 0) && (sum += sum_Solution(n-1)) > 0;
return sum;
}
/**
* 思路:
* 1、使用公式 1+2+...+n = n*(n+1)/2 = (n^2 + n) >> 1
*/
public int sum_SolutionII(int n) {
return ((int)(Math.pow(n, 2)+n)) >> 1;
}
public static void main(String[] args) {
System.out.println(new Sum_Solution().sum_Solution(5));
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.