計算從1到n(包括n)之間出現的各位數字的個數
#include <iostream>
using namespace std;
int countm(int max,const int &n)
{
//在1到max之間的數中,計算數字n出現的次數,並返回
int total=0; //記錄n出現的位數
int num=0; //每個權值內出現的n的個數,如10(1-9)內,1-9各出現一次
int a=1; //操作的位,a等於1時,操作的位為個位,依次類推
int c=0; //每位上出現的數字
int b=0; //當前操作位後的數(如115,現在操作的位為百位1,則b等於15)
while(max>0){
num=num*10+a/10; //權值a內出現的n的個數,如a=100時,num=20;表示每一百個數內出現20個n
b=a*c/10+b; //計算得到b
c=max%10; //得到當前需要處理的位上的數字(0-9)
max=max/10; //得到下一下需要操作的位
if(c>n&&n) total+=a+c*num; //當前位大於n,且n不等於0時,對n出現的次數累加
else if(!n&&c>n) total+=c*num; //當前位大於n,且n等於0時,對n出現的次數累加
else if(c==n) total+=c*num+b+1; //c=n時,對n出現的次數累加
else total+=c*num; //c<n時,對n出現的次數累加
a=a*10; //權值增加,如由10變為100
}
return total; //返回n出現的位數
}
int main()
{
int num; //當前需要操作的數
for(int i=0;i<total;i++)
{
cin>>num; //讀取當前需要操作的數
for (int j=0;j<=9;j++)
cout<<countm(num,j)<<" "; //呼叫countm×),對1-num內出現的j的個數進行計算,並輸出到out.txt檔案
cout<<endl;
}
system("pause");
return 0;
}