C++中统计首位数字相同的数字个数
给定一个区间[first, last]。目标是在此区间内查找首位数字相同的数字的个数。例如,232的首位数字与2相同。
我们将通过从i=first遍历到i=last来实现这一点。对于每个数字,我们将比较它的首位数字与最后一位数字,如果它们相同,则递增计数。
让我们通过例子来理解。
输入 − first=8 last=40
输出 − 首位数字相同的数字个数 − 5
解释 − 8到40之间首位数字相同的数字 − (8, 11, 22, 33, 44)
8, 9, 11, 22, 33
输入 − first=100 last=200
输出 − 首位数字相同的数字个数:5
解释 − 100到200之间首位数字相同的数字 − (101,111,121,131,141,151,161,171,181,191,202)
101, 111, 121, 131, 141, 151, 161, 171, 181, 191.
下面程序中使用的算法如下
我们使用两个整数first和last来定义范围[first,last]。
函数getFirstDigit(int num)接受一个数字并返回它的首位数字。
当num>=10时,将num除以10。最后,num将包含首位数字。返回此值。
函数getCount(int fst,int lst)接受范围变量并返回首位数字相同的数字的个数。
将初始计数设置为0。
使用for循环从i=fst开始到i=lst结束,对于每个i,通过调用getFirstDigit(i)计算其首位数字并存储在fdigit中。(fdigit=getFirstDigit(i))。
计算最后一位数字为ldigit=i%10。
如果ldigit==fdigit,则表示它们相同。递增计数。
返回计数作为结果。
示例
#include <bits/stdc++.h>
using namespace std;
//to find starting digit
int getFirstDigit(int num){
while (num >= 10)
{ num = num/ 10; }
return num;
}
int getCount(int fst,int lst){
int count=0;
for(int i=fst;i<=lst;i++){
int fdigit=getFirstDigit(i);
int ldigit=i%10; //to get last digit
if(fdigit==ldigit) //if both are equal increment count
{ ++count; }
}
return count;
}
int main(){
int first = 10, last = 23;
cout<<"Numbers with same first and last digits:"<<getCount(first, last);
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
Numbers with same first and last digits:2
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP