请问这个数字统计的题该怎么写
数字统计描述
请统计某个给定范围[L, R]的所有整数中,数字2出现的次数。
比如给定范围[2, 22],数字2在数2中出现了1次,在数12中出现1次,在数20中出现1次,在数21中出现1次,在数22中出现2次,所以数字2在该范围内一共出现了6次。
输入
输入共 1 行,为两个正整数 L 和 R,之间用一个空格隔开。
输出
输出共 1 行,表示数字 2 出现的次数。
输入样例 1 输出样例1
2 22 6
#include<iostream> #include<cstdio> #include<cmath> using namespace std; int main() { int min_number,max_number,i,sum=0,temp; printf("请输入2个整数:"); scanf("%d %d",&min_number,&max_number); while(min_number>max_number) { printf("输入数据错误,请重新输入2个整数:"); scanf("%d %d",&min_number,&max_number); } for(i=min_number; i<=max_number; i++) { temp=abs(i); while(temp>0) { if(temp%10==2) sum++; temp/=10; } } printf("共有%d个2\n",sum); return 0; }
unsigned foo( unsigned L, unsigned R ) { unsigned count = 0; for( unsigned i=0; i!=R-L+1; ++i ) for( unsigned t=i+L; t!=0; t/=10 ) count += t%10==2; return count; }
unsigned bar( unsigned L, unsigned R ) { L -= L>0; unsigned count = 0; for( unsigned a=1; 2*a<=R; a*=10 ) count += R/a/10*a + (R/a%10==2)*(R%a+1) + (R/a%10>2)*a - L/a/10*a - (L/a%10==2)*(L%a+1) - (L/a%10>2)*a; return count; }
#include <iostream> using namespace std; unsigned foo( unsigned L, unsigned R ) { L -= L>0; unsigned count = 0; for( unsigned a=1; 2*a<=R; a*=10 ) count += R/a/10*a + (R/a%10==2)*(R%a+1) + (R/a%10>2)*a - L/a/10*a - (L/a%10==2)*(L%a+1) - (L/a%10>2)*a; return count; } int main( void ) { unsigned L, R; cin >> L >> R; cout << foo(L,R) << endl; }