Given two integers L, R, and digit X. Find the number of occurrences of X in all the numbers in the range (L, R) excluding L and R.
Example 1:
Input:
L=10, R=19, X=1
Output:
9
Explanation:
There are 9 1s (11, 12, 13, 14, 15, 16, 17, 18) in the numbers in the range (10,19).
Example 2:
Input:
L=18, R=81, X=9
Output:
7
Explanation:
There are 7 occurrences of the digit 9 in the numbers in the range (18,81).
Your Task:
You don’t need to read input or print anything. Your task is to complete the function countX() which takes three integers L, R, and X as input parameters and returns the number of occurrences of X in the numbers in the range(L, R).
Constraints:
1 <= L< R <= 105
0 <= X <= 9
Explanation:
Here we want to find the number of X’s in between the L and R. [excluding L and R values]
Example: L = 10, R = 19, X = 1
The numbers contains 1 in between 10 to 19
11 12 13 14 15 16 17 18
11 – 2(1's)
12 - 1
13 – 1
count all the 1’s = 9
Approach:
Step 1:
Start a loop from L+1 to R (Here R is Excluded and it will iterate R-1)
Step 2:
Call the countValue(i,X)
Here the method take the number (L->R) and X.
Step 3:
In countValue(i,X) method
Take i as n and iterate until n!=0
take remainder and check the remainder equal to X then count.
after, do the n = n/10 (this will give u the new n value by dividing with 10)
return the count.
public static int countValue(int n,int X){
int c=0;
while(n!=0){
int rem = n%10;
if(rem==X){
c++;
}
n/=10;
}
return c;
}
Step 4:
Every return count is stored in the count variable and finally return the count as answer.
CODE:
public class XInRange {
public static void main(String[] args) {
int L=10, R=19, X=1;
// 11(count=2(1's)) 12 13 14 15 16 17 18
//excluding L and R
System.out.println("How many X's: "+countX(L,R,X));
}
static int countX(int L, int R, int X)
{
int count=0;
for(int i=L+1;i<R;i++){
count+=countValue(i,X);
}
return count;
}
public static int countValue(int n,int X){
int c=0;
while(n!=0){
int rem = n%10;
if(rem==X){
c++;
}
n/=10;
}
return c;
}
}
How many X's: 9
problem: https://www.geeksforgeeks.org/problems/how-many-xs4514/1
Thank you for reading.
Happy Coding :)
Please share any optimized code we can discuss and improve code.