logo CodeStepByStep logo

merge_digit_pairs

Language/Type: Python recursion

Write a recursive function named merge_digit_pairs that accepts an integer parameter n and returns the integer formed by combining each pair of digits from n into a single digit that is their sum. For example, if passed the number 1234, you should combine the digits 12 into 1+2 or 3, and combine the digits 34 into 3+4 or 7, leading to a returned result of 37.

If adding a given pair of digits produces a two-digit number, repeat the process until you have a single-digit number to replace the original pair. For example, if passed the number 1168, the 11 becomes 1+1 or 2, but the 68 becomes 6+8 or 14, so we merge them again by saying that 14 is 1+4 or 5, so the pair 68 turns into 5, leading to an overall result of 25.

If passed a number with an odd number of digits, the first (most significant) digit is left untouched. For example, the number 13372 becomes 169 because the 3+3 becomes 6 and the 7+2 becomes 9. If passed a negative number, perform the same process as usual but return a negative result. For example, when passed -1234, return -37. If passed a single-digit number, simply return that number itself.

The following table shows several calls and their expected return values:

Call Return Value
merge_digit_pairs(1234) 37
merge_digit_pairs(3186507) 3927
merge_digit_pairs(-52874) -512
merge_digit_pairs(88888888) 7777
merge_digit_pairs(20581974) 2412
merge_digit_pairs(0) 0
merge_digit_pairs(6) 6
merge_digit_pairs(6) -5

Constraints: Do not declare any global variables. Also, do not use any loops you must use recursion. Do not use a string to solve this problem. (For example, do not convert n into a string.) You are allowed to define other "helper" functions if you like they are subject to these same constraints.

Function: Write a Python function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.