给我们一个间隔[first,last]。目的是找到具有单位数字k且在范围[first,last]之间的数字的计数。
我们将通过从i = first遍历到i = last来完成此操作。对于每个数字,我将其单位数字与k进行比较,如果它们相同,则递增计数。
让我们通过示例来理解。
输入-first = 8 last = 40,k = 8
输出-单位为k-4的数字计数
说明-
Numbers between 8 and 40 with unit digit = 8 8,18, 28, 38
输入-first = 100 last = 200,k = 9
输出-单位为k-10的数字计数
说明-
Numbers between 100 and 200 with unit digit = 9 109, 119, 129, 139, 149, 159, 169, 179, 189, 199. Total:10
我们首先使用两个整数,然后使用两个整数来定义范围[first,last]。
函数getCount(int fst,int lst,int k)接受范围变量和k,并返回fst和lst之间的数字计数,单位数字为k。
将初始计数设为0。
使用从i = fst到i = lst的for循环开始,对于每个i,我将单位位数计算为ldigit = i%10。
如果ldigit == k,则递增计数。
返回计数作为结果。
#include <bits/stdc++.h>
using namespace std;
int getCount(int fst,int lst,int k){
int count=0;
for(int i=fst;i<=lst;i++){
int ldigit=i%10; //to get last digit
if(ldigit==k) //if both are equal increment count
{ ++count; }
}
return count;
}
int main(){
int first = 5, last = 30;
int K=5;
cout<<"单位数字K在范围内的数字:"<<getCount(first, last, K);
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
单位数字K在范围内的数字:3