Description
The Little Elephant very much loves sums on intervals.
This time he has a pair of integers l and r(l ≤ r). The Little Elephant has to find the number of such integers x(l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.
Help him and count the number of described numbers x for a given pair l and r.
Input
The single line contains a pair of integers l and r(1 ≤ l ≤ r ≤ 1018) — the boundaries of the interval.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Output
On a single line print a single integer — the answer to the problem.
Sample Input
2 47
12
47 1024
98
Hint
In the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44.
一道让我WA 了N次的题目。。。。。可以分别算出从1到l和r的总的数目,然后减一下。对于一个位数为n的大数来说 ,然后对于多出来的n-1的数再进行相加,在加上前面的位数的全排列。最后,相减以后要看那个l,如果l本身也是属于其中的,要加1。。。。。
#include<stdio.h>
#include<math.h>
#include<string.h>
__int64 min(__int64 a,__int64 b){
if(a<b)return a;
else return b;
}
__int64 power(__int64 a,__int64 b)
{
__int64 i;
for(i=1;i<b;i++)
a=a*10;
if(b==0)a=1;
return a;
}
int main()
{
char l[100],r[100];
__int64 i,j,l1,l2,x,y,m;
__int64 t1,t2,t,sum;
while(scanf("%s%s",l,r)!=EOF)
{
t2=0;t1=0;sum=1;
l1=strlen(l);
l2=strlen(r);
x=l1-2;
if(x<0)t1=l[0]-48;
if(x==0){
if(l[0]>l[l1-1])t1=l[0]-1-48;
if(l[0]<=l[l1-1])t1=l[0]-48;
t1=9+t1;}
if(x>0){
sum=1;
m=l[0]-48;
t1=t1+(power(10,x))*(m-1);
if(l[0]>l[l1-1])t1--;
// if(t1<0)t1=0;
for(i=l1-2;i>=1;i--)
{
t1=t1+(l[i]-48)*power(10,l1-2-i);
}
t1++;
// if(t1==1)t1=0;
for(i=x+1;i>=2;i--)
t1=t1+9*power(10,i-2);
t1=t1+9;
}
y=l2-2;
if(y<0)t2=r[0]-48;
if(y==0){
if(r[0]>r[l2-1])t2=r[0]-1-48;
if(r[0]<=r[l2-1])t2=r[0]-48;
t2=9+t2;
}
if(y>0){
sum=1;
m=r[0]-48;
t2=t2+(power(10,y))*(m-1); //printf("%I64d\n",power(10,4));
if(r[0]>r[l2-1])t2--;
// if(t2<0)t2=0;
for(i=l2-2;i>=1;i--)
{
t2=t2+(r[i]-48)*power(10,l2-2-i);
}
// if(t2==1)t2=0;
t2++;
for(i=y+1;i>=2;i--)
{
t2=t2+9*power(10,i-2);
}t2=t2+9;
}
// printf("%I64d %I64d\n",t1,t2);
t=t2-t1;
if(strcmp(l,r)==0)t=0;
if(l[0]==l[l1-1])t++;
printf("%I64d\n",t);
}
}
以上是我的代码,十分复杂。。。
看我队友的代码:
#include <iostream>
#include<stdio.h>
using namespace std;
__int64 Pow(__int64 k)
{
__int64 ans=1;
for(int i=0; i<k; i++)
ans*=10;
return ans;
}
__int64 sum(__int64 a)
{
if(a>=0&&a<=9) return a+1;
__int64 b=a,r=a%10,ans=0;
__int64 i=9,j=0;
while(b>=10)
{
ans+=i;
i*=10;
j++;
b/=10;
}
a/=10;
a-=Pow(j);
if(r>=b) a++;
return a+ans+10;
}
int main()
{
__int64 m,n;
while(scanf("%I64d%I64d",&m,&n)!=-1)
{
m-=1;
printf("%I64d\n",sum(n)-sum(m));
}
return 0;
}