0

I am trying to create a recursive method to find the number of times a specific digit occurs in an integer number. So for example, if number is 13563 and the digit is 3, the method should return 2 since 3 occurs twice in the number. I am confused however as to what my base case should be in situation.

public static int digit(int number, int digit){
if(number.indexOf(0) == digit){
    return 1;
}
else{
    return 1 + digit(number, digit);
}
}
user3328187
  • 193
  • 2
  • 2
  • 6
  • 2
    Calling methods on ints? That's not going to work. Also, not directly related but this might help: http://stackoverflow.com/questions/9533225/how-to-count-how-many-times-a-number-appears-in-a-txt-file – Nico Feb 16 '15 at 03:33
  • 2
    You also have named your method 'digit' and named one of the arguments 'digit'. Even if that worked, it would be a really, really bad idea. – Richard Schwartz Feb 16 '15 at 03:34
  • 2
    @RichardSchwartz it does work AFAIK. It's still a bad idea. – user253751 Feb 16 '15 at 03:39
  • 1
    why you would want to / need to use recursion in this case? – shonky linux user Feb 18 '15 at 05:12

8 Answers8

1

If you want to use recursion, here's the solution:

public static int recurseCountDigits(final int number, final int digit){
    if(number < 10) {
        // if the number is less than 10, return if the digit is present, and don't recurse any deeper
        return number == digit ? 1 : 0;
    } else {
        // if the right-most digit is correct
        if(number%10 == digit) {
            // return 1 + the value from the remaining digits (recursion)
            return 1 + recurseCountDigits(number/10, digit);
        } else {
            // else just return the value from the remaining digits (recursion)
            return recurseCountDigits(number/10, digit);
        }
    }
}

This solution works for non-negative numbers and non-negative digits. Other combinations may or may not work.

Jason
  • 11,744
  • 3
  • 42
  • 46
0

Convert it to a string, then use method described here: Simple way to count character occurrences in a string

String s = "...";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
    if( s.charAt(i) == '$' ) {
        counter++;
    }  
} 

To convert to string:

String.valueOf(number);
Community
  • 1
  • 1
Xeridea
  • 1,146
  • 1
  • 10
  • 17
0

You can do it witout converting to string, by using the mod operator and truncating division, like this: // non-recursive wrapper to handle degenerate case of 0,0 input. publlc static int digitCount(int numberr, digit) { if ((nunmber==0) && (digit == 0)) return 1; else return digitCountr(number, digit); }

public static int digitCountr(int number, int digit){

   if (number == 0)
      return 0;
   if (number % 10 == digit)
      return 1 + digitCount(number / 10, digit);
   else 
      return digitCount(number / 10, digit);
}

This will return 0 when called with the number arg equal to 0, which may not be what you want - but it relies on that actually in order to correctly count any actual zero digits so you'd need to put a wrapper around it if you want different behavior for that case.

  public static int digitCount(int number, int digit) {
        if ((number==0) && (digit == 0))
          return 1;
        else
          return digitCountr(number, digit);
        }

    public static int digitCountr(int number, int digit){

       if (number == 0)
          return 0;
       if (number % 10 == digit)
          return 1 + digitCount(number / 10, digit);
       else 
          return digitCount(number / 10, digit);
    }

Other than that, though, I believe it is accurate.

Richard Schwartz
  • 14,463
  • 2
  • 23
  • 41
0

You can do this easily using modulos, which could avoid you the cost of making a string.

public static int digit(int number, int digit)
{
    if ( number <= 0 ) {
    return 0;
    }
    else {
    if ( number % 10 == digit ) {
        return 1 + digit (number / 10, digit);
    }
    else {
        return digit (number / 10, digit);
    }
    }
}

Now this code wouldn't work for negative or null numbers and it is not tail recursive so we could make it better.

public static int digit_aux (int number, int digit, int result)
{
    if ( number == 0 ) {
        return result;
    }
    else {
    return digit_aux (number / 10, digit,
                      result + ( ( number % 10 == digit ) ? 1 : 0) );
    }
}


public static int digit (int number, int digit)
{
  if ( number == 0 ) {
   return  (digit == 0) ? 1 : 0;
  }
  else {
   return digit_aux ( Math.abs(number), digit, 0);
  }
}

This is the good way to do recursion (even though I'm not sure Java has developed tail-call optimization yet).

PatJ
  • 5,996
  • 1
  • 31
  • 37
0

Ofcourse if you are not specific of recursive methodology... I have solution to solve the count

        int i = 13563;
           Integer u = new Integer(i);

           Map<Integer, Integer> m = new HashMap<Integer, Integer>();
           String s = u.toString();
           char c []=s.toCharArray();

           for (int j=0;j<c.length;j++)
           {


               if(m.containsKey(Integer.valueOf(String.valueOf(c[j]))))
               {

                   int k = m.get(Integer.valueOf(String.valueOf(c[j])));

                   m.put(Integer.valueOf(String.valueOf(c[j])), k+1);

               }else{
                   m.put(Integer.valueOf(String.valueOf(c[j])),1);

               }


           }

           System.out.println("The index digit is 3 count is --> "+m.get(3));
Rookie007
  • 1,229
  • 2
  • 18
  • 50
0
public class code {

    public int count(int N)
    {

            int  i, j, r = 0 , count = 0;


            for(i = 1; i <= 13; i++) {
            j = i;
            while(i >= 10) {
            i = i / 10;
            r = j % 10;
            }
            if(i == 1) {
                count = count + 1;
                }
            if (r == 1)
            {
                count = count+1;
                r=0;
            }
                i = j;
                }
           return count;



                }
public static void main (String args[])
    {
        code c = new code();
    System.out.println(c.count(13));
    }
}

output: 6

-1

The first problem I notice with your code is that it will return 1 if the first digit of the number matches the digit your looking for. What if you pass the number 1145? It would return 1 instead of 2.

A good base case would be checking to see if the number passed is valid (if not return 0), otherwise iterate through each digit (recursively) using a counter to count how many times the digit occurs. I noticed @Jean-François Savard posted a pretty good code example for you.

Srx2020
  • 13
  • 2
  • 4
-1

Of course if you didn't need to use recursion it is a one liner using StringUtils

StringUtils.countMatches(Integer.toString(number), Integer.toString(digit));

I realise this is not answering the question but you haven't specified why you would want / need to use recursion in this case... Is it homework perhaps?

shonky linux user
  • 6,131
  • 4
  • 46
  • 73
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Radiodef Feb 18 '15 at 04:38
  • NP... I have added a comment . But I have provided the alternative simple answer because in normal circumstances one would not use recursion to count occurrences of a digit. – shonky linux user Feb 18 '15 at 05:15