递归java代码_java代码实现递归

think in java 书中使用递归分析

代码如下:

public class Snake implements Cloneable {

private Snake next;

private char c;

// Value of i == number of segments

Snake(int i, char x) {

c = x;

if(--i > 0)

next = new Snake(i, (char)(x + 1));

}

void increment() {

c++;

if(next != null)

next.increment();

}

public String toString() {

String s = ":" + c;

if(next != null)

s += next.toString();

return s;

}

public Object clone() {

Object o = null;

try {

o = super.clone();

} catch (CloneNotSupportedException e) {}

return o;

}

public static void main(String[] args) {

Snake s = new Snake(5, 'a');

System.out.println("s = " + s);

Snake s2 = (Snake)s.clone();

System.out.println("s2 = " + s2);

s.increment();

System.out.println(

"after s.increment, s2 = " + s2);

}

}

示意图如下:

bc100729eacbd948db2ab426bb1e1705.png

输出如下:

s = :a:b:c:d:e

s2 = :a:b:c:d:e

after s.increment, s2 = :a:c:d:e:f

分析:

在讲clone()的时候,为说明浅复制,举例此类;

一条 Snake(蛇)由数段构成,每一段的类型都是 Snake。所以,这是一个一段段链接起来的列表。

所有段都是以循环方式创建的,每做好一段,都会使第一个构建器参数的值递减,直至最终为零。

而为给每段赋予一个独一无二的标记,第二个参数(一个 Char )的值在每次循环构建器调用时都会递增。

increment()方法的作用是循环递增每个标记,使我们能看到发生的变化;

而 toString 则循环打印出每个标记。

使用递归打印阶乘

@Test

public void test() {

//10! = 10 * 9 * 8 * 。。。。1;

System.out.println(get(36));

}

public static long get(int n) {

long result = 1;

if (n == 1) {

result *= 1;

}

else {

result = n * get(n-1);

}

return result;

}

使用递归打印斐波那契数列

//第一和第二项是1,后面每一项是前二项之和,即1,1,2,3,5,8,13,...。

//递归实现:

public static int fun02(int n) {//n是第n个数,从 0 开始

if (n > 1) {

return (fun02(n-1) + fun02(n-2));

}else {

return 1;

}

}

public static void main(String[] args) {

for (int i = 0; i <= 9; i++) {

System.out.println(fun02(i));

}

}

使用递归打印 9 * 9乘法口诀表

public class multiplication99 {

@Test

public void test(){

//getByFor(9);

getByRecursion(9);

}

public static void getByFor(int n) {//for 循环实现

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(i+" * "+j+" = "+i*j+" ");

}

System.out.println();

}

}

public static void getByRecursion(int n) {//递归 实现

if (n == 1) {

System.out.println("1 * 1 = 1 ");

}

else {

getByRecursion(n-1);

for (int j = 1; j <= n; j++) {

System.out.print(n+" * "+j+" = "+n*j+" ");

}

System.out.println();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值