方法一:窮舉
///偉人 E-mail:abigwc@gmail.com QQ:270173053 歡迎交流// #include<stdio.h> int main() { unsigned int L,R,i,count=0,temp; FILE *in,*ou; if((in=fopen("two.in","r"))==NULL) { printf("Can not open the input file."); exit(0); } if((ou=fopen("two.ou","w"))==NULL) { printf("Can not open the output file."); exit(0); } fscanf(in,"%u%u",&L,&R); for(i=L;i<=R;i++) { temp=i; while(temp!=0) { if(temp%10==2) count++; temp=temp/10; } } fprintf(ou,"%u",count); fclose(in); fclose(ou); return 0; }
方法二:從數學上分析
//偉人 E-mail:abigwc@gmail.com QQ:270173053 歡迎交流// #include<stdio.h> int Get2Count(unsigned int N) { unsigned int p=1,count=0,right=0,left=N,current; while(left!=0) { current=left%10; left=left/10; if(current<2) { count+=left*p; } else if(current==2) { count+=left*p+right+1; } else count+=(left+1)*p; right=right*10+current; p*=10; } return count; } int main() { unsigned int L,R; FILE *in,*ou; if((in=fopen("two10.in","r"))==NULL) { printf("Can not open the input file."); exit(0); } if((ou=fopen("two.ou","w"))==NULL) { printf("Can not open the output file."); exit(0); } fscanf(in,"%u%u",&L,&R); fprintf(ou,"%u",Get2Count(R)-Get2Count(L)); fclose(in); fclose(ou); return 0; }