Occurance of a digit in an Integer recursively

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
 
---------------------------------
public int count7(int n) {


int count=0;



int rtemp=0;

int ltemp=0;


if(n/10<10 ){

rtemp=n%10;

ltemp=n/10;


if(ltemp==7)

count=count+1;

if(rtemp==7)

count=count+1;

}


else{

rtemp=n%10;

ltemp=n/10;

count=count+count7(ltemp);

if(rtemp==7)

count=count+1;


}



return count;

}

Comments

Popular posts from this blog

defining functions clojure

Integrating Struts2 with Spring Security using Custom Login Form