`

求1+2+…+n

阅读更多

求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。

 第一种解法 递归,用hashmap 来选择A和SumN的不同sum方法,最终用A的sum方法终止递归。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

class A{
	public  long sum(long i){
		return 0;
	}
}


public class SumN extends A {
    public static HashMap<Boolean,A> a= new HashMap<Boolean,A>();
	
	public  long sum(long i){
		return i+a.get(i==0).sum(i-1);
	}
	
	
	public static void main(String [] args) throws NumberFormatException, IOException{
		long n = 1000L;
		a.put(true, new A());
		a.put(false, new SumN());
		/*System.out.println("Enter a number:\n");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s="";
		while((s=br.readLine())!=null&&s.length()!=0){
		int n = Integer.parseInt(s.trim());
		br.close();
		*/
		System.out.println("sum "+a.get(false).sum(n));
		
		
	}
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics