(Luogu) P1980 counting issue submitted

(Programs involving many variables must be clearly commented)

#include <iostream>

using namespace std;

int main() {
	int n=0;//区间 1 到 n 的 n
	int x=0;//出现的数字
	int num=0;//出现的数字次数
	cin >> n >> x;

	for (int i = 1;i<=n; i++) {
		int b = i;

		while (b != 0) {
			int c = b % 10;
			if (x == c) {
				num++;
			}
			b = b / 10;
		}
	}
	cout << num << endl;

	return 0;
}

2. (Use function method)

#include <iostream>

using namespace std;

void js(int n, int x) {
	int num = 0;
	for (int i = 1; i <= n; i++) {
		int b = i;

		while (b != 0) {
			int c = b % 10;
			if (x == c) {
				num++;
			}
			b = b / 10;
		}
	}
	cout << num << endl;
}

int main() {
	int n = 0;//区间 1 到 n 的 n
	int x = 0;//出现的数字
	int num = 0;//出现的数字次数
	cin >> n >> x;
	js(n, x);

	return 0;
}

3. (Solution of a Luogu boss)
In a real game, just think of an algorithm that can ac, but in practice, you still have to exercise your thinking and think about better algorithms. It is not difficult to find that even without a computer, the answer is easy to find, such as:

n=728,x=7

You can follow this idea:

Units 7: 73 7,17,...,727

Tenth place 7: 70 70 79 , 170 179,...,670~679

Hundreds 7: 29 700~728

The answer is 172

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
    int n,x,m=1,ans=0;
    scanf("%d%d",&n,&x);
    while(m<=n){
        int a=n/(m*10),b=n/m%10,c=n%m; //a,b,c为n的三部分,求哪一位x的个数,b就为那一位数,a为b左边的数,c为b右边的数,如求1~728中十位7的个数,则a=7,b=2,c=8
        if(x){
            if(b>x) ans+=(a+1)*m; //如果b>x,说明有(a+1)*m个x(如求1~728中个位7的个数,则为(72+1)*1=73)
            if(b==x) ans+=a*m+c+1; //如果b=x,说明有a*m+c+1个x(如求1~728中百位7的个数,则为0*100+28+1=29)
            if(b<x) ans+=a*m; //如果b<x,说明有a*m个x(如求1~728中十位7的个数,则为7*10个)
        }
        else{ //x=0的情况和x!=0的情况有所不同
            if(b) ans+=a*m;
            else ans+=(a-1)*m+c+1;
        }
        m*=10;
    }
    printf("%d\n",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44093867/article/details/98798687