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;//111111111while(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; }總結
思考得出
總結
以上是生活随笔為你收集整理的B. Ordinary Numbers的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: ThinkPad 宝典全集
- 下一篇: 读《Python Algorithms:
