题目
Let’s call a positive integer n ordinary if in the decimal notation all its digits are the same. For example, 1, 2 and 99 are ordinary numbers, but 719 and 2021 are not ordinary numbers.
For a given number n, find the number of ordinary numbers among the numbers from 1 to n.
输入格式
The first line contains one integer t (1≤t≤104). Then t test cases follow.
Each test case is characterized by one integer n (1≤n≤109).
输出格式
For each test case output the number of ordinary numbers among numbers from 1 to n.
数据范围
10的九次方
样例输入
6
1
2
3
4
5
100
样例输出
1
2
3
4
5
18
题意
多组输入输出
找到1-n的范围内有几个类似111这样的,每一位都相同的数
思路
- 1.1-10里有9个
- 2.11-100里有9个
- 3.101-1000里有九个
- 4.以此类推…
- 5.先找这个数的范围,用while分解每一位,每分解一位就+9,cnt初始化为-9,因为比如100,其实只到第二个范围,如果不减9就到第三个范围了
- 6.然后给的数万一不是一个正好的整数,比如23456,我们根据上一步操作只找到了1-10000里的符合要求的数的数量,要找10001-23456里有几个符合要求的数,就用23456/11111,再加上之前的结果就是要求的数
坑点
- 1.1
- 2.3
- 3.3
代码
原版
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long int n;
cin>>n;
while(n--)
{
long long int a;
cin>>a;
if(a<10)
{
cout<<a<<endl;
}
else
{
long long int cnt=-9;
long long int x=a;
long long int sum=1;//1000000000
long long int sum1=0;//111111111
while(x>0)
{
f=x%10;
x/=10;
sum=sum*10;
sum1=sum1*10+1;
cnt+=9;
}
//cout<<f<<endl;
/*sum=sum/10*f;
a-=sum;
sum1/=10;
cnt=cnt+a/sum1;*/
cnt+=a/sum1;
cout<<cnt<<endl;
}
}
return 0;
}
简化版1
#include<iostream>
int main()
{
long long int n;
scanf("%lld",&n);
while(n--)
{
long long int a;
scanf("%lld",&a);
if(a<10)
{
printf("%lld\n",a);
}
else
{
long long int cnt=-9,x=a,sum1=0;
while(x>0)
{
x/=10;
sum1=sum1*10+1;
cnt+=9;
}
cnt+=a/sum1;
printf("%lld\n",cnt);
}
}
return 0;
}
最终简化版(length:311 , time:31ms)
#include<iostream>
int main()
{
long long int n;
scanf("%lld",&n);
while(n--){
long long int a;
scanf("%lld",&a);
if(a<10) printf("%lld\n",a);
else{
long long int cnt=-9,x=a,sum1=0;
while(x>0){
x/=10;
sum1=sum1*10+1;
cnt+=9;}
cnt+=a/sum1;
printf("%lld\n",cnt);}}
return 0;
}
总结
思考得出