GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — zc/newcoder/codinginterviews/Sum_Solution.java at master · codeaike/zc Expand file tree/ Copy pathSum_Solution.javaMore file actions 39 lines (32 loc) · 875 Bytes / Copy pathSum_Solution.javaFile metadata and controls39 lines (32 loc) · 875 Bytes 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. |