10-04-2015 Recursion

BJP3 Exercise 12.10: digitMatch

Status: not solved  You have solved this problem; good work!
Added by:Robert Baxter on 2013/04/01
Language:Java
Keywords: recursion
Popularity: 30 likes  icon Like

Write a recursive method digitMatch that accepts two non-negative integers as parameters and that returns the number of digits that match between them. Two digits match if they are equal and have the same position relative to the end of the number (i.e. starting with the ones digit). In other words, the method should compare the last digits of each number, the second-to-last digits of each number, the third-to-last digits of each number, and so forth, counting how many pairs match. For example, for the call ofdigitMatch(1072503891, 62530841), the method would compare as follows:

1 0 7 2 5 0 3 8 9 1
    | | | | | | | |
    6 2 5 3 0 8 4 1

The method should return 4 in this case because 4 of these pairs match (2-2, 5-5, 8-8, and 1-1). Below are more examples:

Call Value Returned
digitMatch(38, 34) 1
digitMatch(5, 5552) 0
digitMatch(892, 892) 3
digitMatch(298892, 7892) 3
digitMatch(380, 0) 1
digitMatch(123456, 654321) 0
digitMatch(1234567, 67) 2

Your method should throw an IllegalArgumentException if either of the two parameters is negative. You are not allowed to construct any structured objects other than Strings (no array, ListScanner, etc.) and you may not use any loops to solve this problem; you must use recursion.


搜来的答案:

public int digitMatch(int x, int y){
    if(x < 0 || y < 0){
      throw new IllegalArgumentException();
    }
      else if(x < 10 || y < 10){
         if(x % 10 == y % 10)
            return 1;
         else
             return 0;
      } else if( x % 10 == y % 10){
         return 1 + digitMatch(x/10, y/10);
      } else{
         return digitMatch(x/10,y/10);
    }
}


我的草稿:

public static int digitMatch(int n1, int n2) {
        if (n1 < 0 || n2 < 0) {
            throw new IllegalArgumentException();
        }else if(n1 ==0 || n2==0){
            return 0;
        } else {
            if (n1 % 10 == n2 % 10) {
                return 1 + digitMatch(n1 / 10, n2 / 10);
            } else {
                return 0 + digitMatch(n1 / 10, n2 / 10);
            }
        }
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值