Recursion, Java

0 Suleman Ahmed · May 8, 2015
Hey, i have trouble with this exercise. I just cannot seem to get the right idea to solve this problem. 

 4. Write a recursive method called doubleDigits that accepts an integer n as a parameter and returns the integer
 obtained by replacing every digit of n with two of that digit. For example, doubleDigits(348) should return
 334488. The call doubleDigits(0) should return 0. Calling doubleDigits on a negative number should return
 the negation of calling doubleDigits on the corresponding positive number; for example, doubleDigits(-789)
 should return -778899.

public class Opgave4 {
public static void main(String[] args) {



public static int doubleDigit(int n) {
if (n == 0) {
return 0;
else if (??) {
else {
return n;

I would appreciate if someone could give me some hints. 

Post a Reply


Oldest  Newest  Rating
+2 Sharon Fabin · May 8, 2015
hey all you need to do is to handle one digit at a time and change its value so it will be displayed as a double digit e.g. 8->88.
to do that you need to choose a path - go from the left to right or vice versa. if you go from left to right you need to call the function 
doubleDigits(n%10) or if you want from the right to the left you need to call doubleDigits(n/10). 
when you choose a path you need to handle the digit that is going to be cancelled on the next recursion. if you go from right to left you need to save the first digit value + the digit value times 10 and that will give the effect of a double digit. and on the next recursion, you need to multiply the whole number by 100 so the values wont add up on each other so it will give the effect of doubled digits.
if you're going from the left to the right you need to first multiply the digit by a big number so it wont add up with the next digits, and for that you need to come up with an algorithem.

SPOILER ALERT - if you dont want to see the code dont read the next lines.

//from right to left

public static int doubleDigit(int amt) {
   if (amt == 0) return 0;     
   return  amt%10 + amt%10*10 + doubleDigit(amt/10)*100;    

//from left to right

public static int doubleDigit(int n){
if(Math.abs(n)<10) return n+n*10;
int dec=1;
for(int i=Math.abs(n);i>9;i/=10){
int num=n/dec;
return ((num*dec*dec)+(num*dec*dec*10))+doubleDigit(n%dec);
0 Suleman Ahmed · May 9, 2015
Thank you sir. The hint you gave was what i needed. 
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator