Search code examples
javarecursionsumdigits

Recursive method that finds the difference between the number of digits in 2 given ints


The input is two given ints, which are both N numbers, the output has to be the result of the difference. For example, for the first number being 1234 and the second being 1, the output has to be 3. I tried writing a recursive method but it won't let me subtract them, saying required two ints but found one. Here is the code so far:

public static int digitDiffer (int a, int b){
   int sumA = 0;
   int sumB = 0;
   if(a == 0 && b==0){
     return 0;
   }
   else {
     sumA += a % 10;
     a /= 10;
     sumB += b % 10;
     b /= 10;
   }
   return digitDiffer (sumA-sumB);
 }

Solution

  • This is my approach

    public static int digitDiffer (int a, int b){
            // I will divide a and b by 10 until one of them is 0
            if(a != 0 && b != 0) return digitDiffer(a/10, b/10);
    
            //if b == 0 and a != 0 then I will count how many times I can divide a by 10 until it becomes 0
            if(a != 0 && b == 0) return 1 + digitDiffer(a/10, 0);
    
            // if a == 0 and b != 0 then I will count how many times I can divide b by 10 until it becomes 0
            if(a == 0 && b != 0) return 1 + digitDiffer(0, b/10);
            return 0;
        }
    

    Output Example: for a = 12345 and b=1 the output will be: 4