Java > Recursion-1 > count7 (CodingBat Solution)

Problem:

Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

count7(717) → 2
count7(7) → 1
count7(123) → 0


Solution:

public int count7(int n) {
  if (n < 1) return 0;
  if (n % 10 == 7) return 1 + count7(n/10);
  else return count7(n/10);
}


10 comments :

  1. int count=0;
    if(n<1) return 0;
    if(n%10==7) count++;
    return count +count7(n/10);

    ReplyDelete
    Replies
    1. count just switches back to 0 each method call...unne unnecessary memory usage

      Delete
  2. How can I do this with while loop?

    ReplyDelete
  3. public int count7(int n) {
    if(n == 0) {
    return 0;
    }

    if(n % 10 == 7) {
    return 1 + count7(n / 10);
    } else {
    return count7(n / 10);
    }
    }

    ReplyDelete
  4. static int countOf7s=0;
    public static int getCountOf7s(int intVal) {
    while(intVal>6){
    if(intVal==7 || intVal%10==7) {
    countOf7s++;
    }
    intVal=intVal/10;
    }
    return countOf7s;
    }

    Would this be bad code?

    ReplyDelete
  5. int count = 0;
    while (n != 0) {
    if (n % 10 == 7) {count++;}
    n /= 10;
    }return count;

    ReplyDelete
    Replies
    1. no its asking recursive that require base step which is all positive numbers and recursive method means it calls the same method instead the method.

      Delete
  6. public int count7(int n) {
    if(n<0)throw new IllegalArgumentException("require positive number");
    if(n==0)return 0;
    else {
    return (n%10==7)?1+count7(n/10):count7(n/10);
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact