看视频看到递归知识点时练练手
/*
用for循环和递归方式求0到某个数之间的双数的和
*/
class TestDemo
{
public static void main(String[] args)
{
System.out.println(getDoubleSum1(9));
System.out.println(getDoubleSum2(9));
}
public static int getDoubleSum1(int num){
int sum=0;
for(int i=num;i>0;i--)
{
if(i%2==0)
sum+=i;
}
return sum;
}
public static int getDoubleSum2(int num){
if(num==0)
return 0;
if(num%2==0)
{return num+getDoubleSum2(num-2);}
else
{
num=num-1;
return getDoubleSum2(num);
}
}
}
|
|