logo Practice-It logo

digitMatch

Language/Type: Java recursion recursive programming
Author: Stuart Reges (on 2014/02/13)

Write a recursive method digitMatch that takes two nonnegative 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 relative position starting from 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 digitMatch(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:

    Method 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 to solve this problem (no array, String, StringBuilder, ArrayList, etc) and you may not use a while loop, for loop or do/while loop to solve this problem; you must use recursion.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.