B. Ordinary Numbers

题目

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;
}

总结

思考得出

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值