Count of numbers from range [L, R] that end with any of the given digits
Given a range [L, R], the task is to find the count of numbers from the range whose last digit is either 2, 3 or 9.
Examples:
Input: L = 1, R = 3
Output: 2
2 and 3 are the only valid numbers.
Input: L = 11, R = 33
Output: 8
Approach: Initialize a counter count = 0 and run a loop for every element from the range, if the current element ends with any of the given digits then increment the count.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int countNums( int l, int r)
{
int cnt = 0;
for ( int i = l; i <= r; i++)
{
int lastDigit = (i % 10);
if ((lastDigit % 10) == 2 || (lastDigit % 10) == 3
|| (lastDigit % 10) == 9)
{
cnt++;
}
}
return cnt;
}
int main()
{
int l = 11, r = 33;
cout << countNums(l, r) ;
}
|
Java
class GFG {
static int countNums( int l, int r)
{
int cnt = 0 ;
for ( int i = l; i <= r; i++) {
int lastDigit = (i % 10 );
if ((lastDigit % 10 ) == 2 || (lastDigit % 10 ) == 3
|| (lastDigit % 10 ) == 9 ) {
cnt++;
}
}
return cnt;
}
public static void main(String[] args)
{
int l = 11 , r = 33 ;
System.out.print(countNums(l, r));
}
}
|
Python3
def countNums(l, r) :
cnt = 0 ;
for i in range (l, r + 1 ) :
lastDigit = (i % 10 );
if ((lastDigit % 10 ) = = 2 or (lastDigit % 10 ) = = 3
or (lastDigit % 10 ) = = 9 ) :
cnt + = 1 ;
return cnt;
if __name__ = = "__main__" :
l = 11 ; r = 33 ;
print (countNums(l, r)) ;
|
C#
using System;
class GFG
{
static int countNums( int l, int r)
{
int cnt = 0;
for ( int i = l; i <= r; i++)
{
int lastDigit = (i % 10);
if ((lastDigit % 10) == 2 ||
(lastDigit % 10) == 3 ||
(lastDigit % 10) == 9)
{
cnt++;
}
}
return cnt;
}
public static void Main()
{
int l = 11, r = 33;
Console.Write(countNums(l, r));
}
}
|
Javascript
<script>
function countNums(l, r)
{
let cnt = 0;
for (let i = l; i <= r; i++) {
let lastDigit = (i % 10);
if ((lastDigit % 10) == 2 || (lastDigit % 10) == 3
|| (lastDigit % 10) == 9) {
cnt++;
}
}
return cnt;
}
let l = 11, r = 33;
document.write(countNums(l, r));
</script>
|
Time Complexity: O(r)
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
28 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...