关于Java的recursion的问题 50

想要一个程序。要求你输入数字。输入0的时候输出以下TheminimumnumberisThesumofpositivenumbersisThesumofnumbersat... 想要一个程序。要求你输入数字。输入0的时候输出以下
The minimum number is
The sum of positive numbers is
The sum of numbers at even indexes is
The total count of odd integers is

要求不能用loop在
public static int findMin(int[] numbers, int startIndex, int endIndex)
public static int computePositiveSum(int[] numbers, int startIndex, int endIndex)
public static int computeSumAtEven(int[] numbers, int startIndex, int endIndex)
public static int countOdd(int[] numbers, int startIndex, int endIndex)

但是输入array的时候可以用loop饿
各位大神求助啦。
小弟初学是在不太会这个
展开
 我来答
百度网友9308069
2012-11-29 · TA获得超过1万个赞
知道大有可为答主
回答量:3947
采纳率:89%
帮助的人:1890万
展开全部
全当练习,自己不做,总学不会,用的分治算法

import java.util.Scanner;
public class Test{
public static int findMin(int[] numbers, int startIndex, int endIndex){
if(startIndex>=endIndex-1)
return numbers[startIndex];
int mid=(startIndex+endIndex)/2;
//System.out.println("start:"+startIndex+"end:"+endIndex+" mid:"+mid);
int left=findMin(numbers, startIndex, mid);
int right=findMin(numbers, mid, endIndex);
return left<=right?left:right;

}
public static int computePositiveSum(int[] numbers, int startIndex, int endIndex){
if(startIndex>=endIndex-1)
return numbers[startIndex]>0?numbers[startIndex]:0;
int mid=(startIndex+endIndex)/2;
return computePositiveSum(numbers, startIndex, mid)+computePositiveSum(numbers, mid, endIndex);
}
//由于java数组的下标是从0算起,0,1,2,3,4,5,取偶数0,2,4
public static int computeSumAtEven(int[] numbers, int startIndex, int endIndex){
if(startIndex>=endIndex-1)
return startIndex%2==0?numbers[startIndex]:0;
int mid=(startIndex+endIndex)/2;
return computeSumAtEven(numbers, startIndex, mid)+computeSumAtEven(numbers, mid, endIndex);
}
public static int countOdd(int[] numbers, int startIndex, int endIndex){
if(startIndex>=endIndex-1)
return numbers[startIndex]%2==0?0:1;
int mid=(startIndex+endIndex)/2;
return countOdd(numbers, startIndex, mid)+countOdd(numbers, mid, endIndex);
}
public static void main(String[] args) {

Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
//int a[]={3,4,1,6,7};
System.out.println("The minimum number is "+findMin(a,0,a.length)+
"\nThe sum of positive numbers is "+computePositiveSum(a,0,a.length)+
"\nThe sum of numbers at even indexes is "+computeSumAtEven(a,0,a.length)+
"\nThe total count of odd integers is "+countOdd(a,0,a.length)
);
}
}

5
4 3 1 5 -2
The minimum number is -2
The sum of positive numbers is 13
The sum of numbers at even indexes is 3
The total count of odd integers is 3
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式