文章

5

粉丝

138

获赞

6

访问

24.4k

头像
递归取余求解
P1002 兰州大学机试题
发布于2022年6月9日 21:10
阅读数 5.2k

求解每一位上含 “2” 的数量,直观方法是每次模10取最后一位数,再除以10去掉最后一位。

没给数据范围,一般不会特别大,递归求解即可。

#include <iostream>
using namespace std;
int calc(int n, int cnt) {
	if(n == 0) return cnt;
	if(n%10 == 2) cnt++;
	return calc(n/10, cnt);
}
int main() {
	int L, R;
	while(cin >> L >> R) {
        int res = 0;
		for(int i = L; i <= R; i++) {
			res += calc(i, 0);
		}
		cout << res << endl;
	}
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发