08-04-2015 Recursion

今天做了一道recursion的题目,好了好久。还是半懂不懂。

BJP3 Exercise 12.3: writeSequence

Status: solved  solved (04/08)
Added by:Marty Stepp on 2013/04/01
Language:Java
Keywords: recursion
Popularity: 30 likes  icon Like

Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed by ascending integers beginning with 1, as in the table below:

Call Output
writeSequence(1); 1
writeSequence(2); 1 1
writeSequence(3); 2 1 2
writeSequence(4); 2 1 1 2
writeSequence(5); 3 2 1 2 3
writeSequence(6); 3 2 1 1 2 3
writeSequence(7); 4 3 2 1 2 3 4
writeSequence(8); 4 3 2 1 1 2 3 4
writeSequence(9); 5 4 3 2 1 2 3 4 5
writeSequence(10); 5 4 3 2 1 1 2 3 4 5

Notice that for odd numbers the sequence has a single 1 in the middle while for even values it has two 1s in the middle.

Your method should throw an IllegalArgumentException if passed a value less than 1. A client using this method would have to callprintln to complete the line of output.


搜到的答案:

public void writeSequence(int n){
    if( n < 1){
        throw new IllegalArgumentException();
    }
    if(n==1){
        System.out.print(n);
    }
    else if(n==2){
        System.out.print(n/2 +" " + n/2);
    }
    else if(n%2 ==0){
        System.out.print(n/2 +" ");
        writeSequence(n-2);
        System.out.print(" " +n/2);
    }
    else if(n%2 ==1){
        System.out.print( (n/2+1) +" ");
        writeSequence(n-2);
        System.out.print( " "+(n/2 +1));
    }
}


我自己的草稿:

 public static void writeSequence(int n) throws IllegalArgumentException { 
        if (n < 1) {
            throw new IllegalArgumentException("IllegalArgumentException");
        } else if (n == 1) {
            System.out.print(1);
        } else {
            System.out.print(n + ", ");
            writeSequence(n - 1);
            System.out.print(", " + n);
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值