##
**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); }

can you explain this ?

ReplyDeleteint count=0;

ReplyDeleteif(n<1) return 0;

if(n%10==7) count++;

return count +count7(n/10);

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

DeleteHow can I do this with while loop?

ReplyDeletepublic int count7(int n) {

ReplyDeleteif(n == 0) {

return 0;

}

if(n % 10 == 7) {

return 1 + count7(n / 10);

} else {

return count7(n / 10);

}

}

static int countOf7s=0;

ReplyDeletepublic 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?

r

ReplyDeleteint count = 0;

ReplyDeletewhile (n != 0) {

if (n % 10 == 7) {count++;}

n /= 10;

}return count;