id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

frew@mclean.com recursion-3 > mergeDigitPairs
prev  |  next  |  chance

Write a recursive method named mergeDigitPairs 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.

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" methods if you like; they are subject to these same constraints.


mergeDigitPairs(1234) → 37
mergeDigitPairs(3186507) → 3927
mergeDigitPairs(-52874) → -512

...Save, Compile, Run (ctrl-enter)

public int mergeDigitPairs(int n) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 200

Copyright Nick Parlante 2017 - privacy