Java實現遞歸經典案例——三角數字的多種實現方式
三角數字的定義就是:第n個三角數字是 由 1+...+n 所得。1、的三角數字是 1
2、的三角數字是 1 + 2 = 3
3、的三角數字是 1 + 2 + 3 = 6
1、while循環實現的方式
public int getTriangleNumber(int n)
{
int totle = 0;
while(n>0) // 從1 開始
{
totle = totle+(n--);
}
return totle;
}
2、for循環方式實現
public int getTriangleNumberByFor(int n)
{
int totle = 0;
for(;n> 0; )
{
totle = totle + n;
}
return totle;
}
3、數學公式方式實現
public int getTriangleNumberByMath(int n)
{
return (n*n + n)/2;
}
4、遞歸方式實現
public int getTriangleT(int n)
{
int totle = 0;
if(n == 1)
{
return 1; // 退出遞歸條件,基值情況(base case)
}
return totle = n + getTriangleT(n-1);
}
原帖地址:https://blog.csdn.net/u010708203/article/details/9286885
最後更新:2017-04-03 20:19:07