Fancy Mouse
- -|||
有谁这道题用搜索的么?
注意分段分析。譬如对于123456789,我们这样来计算:
分析1~99999999;
分析100000000~119999999;
分析120000000~123999999;
……
这样做有什么好处呢?注意0~10^n-1的话,每一个数字出现的次数都是相同的(首位0另外考虑),而且可以通过简单的计算就能得到。我们把一个数分段,分成几个0~10^n-1的段,然后再计算。注意100000000~119999999的时候要记住不要忘记加上首位20000000个1哦~~~
#include<iostream>
using namespace std;

void Init(long _result[]);
long pow10(int exp);
long times(long num,int digit,int pos);
int main()
{
    
long i,result[10];
    
while(cin>>i)
    
{
        Init(result);
        
int c,flag=0;
        
long temp=i;
        
while(temp>0)
        
{
            flag
++;
            temp
/=10;
        }

        
for(c=0;c<10;c++)
            
for(int d=0;d<flag;d++)
                result[c]
+=times(i,c,d);
        
for(c=0;c<10;c++)
            cout
<<result[c]<<endl;
    }

    
return 0;
}

void Init(long _result[])
{
    
for(int i=0;i<10;i++) _result[i]=0;
}

long pow10(int exp)
{
    
if(-1==exp) return 0;
    
long result=1;
    
for(;exp>0;exp--) result*=10;
    
return result;
}

long times(long num,int digit,int pos)
{
    
long factor1,factor2,d,result,temp=pow10(pos);
    factor1
=num/temp/10;
    factor2
=num%temp+1;
    d
=(num/temp)%10;
    result
=factor1*temp;
    
if(d==digit) result+=factor2;
    
if(0==digit) result-=temp;
    
if(d>digit) result+=temp;
    
return result;
}
posted on 2005-09-24 13:16  Fancy Mouse  阅读(341)  评论(1编辑  收藏  举报