GESP C++ Level 2 Practice: Counting Digits

GESP Level 2 practice, involving multiple layers of conditions and nested loops, difficulty ★✮☆☆☆.

luogu-t259142 – Counting Digits

Problem Requirements

Problem Description

Calculate how many times the digit () appears among all integers in the interval to . For example, in the interval to , that is, in , the digit appears times.

Input Format

Two integers , separated by a space.

Output Format

An integer representing the number of times appears.

Sample Input #1

11 1

Sample Output #1

4

Data Range

For the data of ,,.

Problem Analysis

In this problem, we need to count how many times the digit appears among all integers in the interval to . We can achieve this by iterating through all integers from to and decomposing each integer to count how many times it contains .

First, we need to read the two input integers and . Then, we use a loop to iterate through all integers from to . In each iteration, we decompose the current integer and count how many times it contains .

During the decomposition, if the last digit of the current integer equals , we increment the counter by one. Finally, we output the value of the counter, which is the number of times the digit appears among all integers in the interval to .

The time complexity of this problem is , and the space complexity is .

Example Code

#include <iostream>
using namespace std;
int main() {
    int n, x, ans = 0; // Define variables n, x, and counter ans
    cin >> n >> x; // Read input n and x
    for (int i = 1; i <= n; i++) { // Outer loop, iterate through all integers from 1 to n
        int tmp = i, num; // Define temporary variables tmp and num
        while (tmp != 0) { // Inner loop, decompose the current integer
            num = tmp % 10; // Get the last digit of the current integer
            if (num == x) // If the last digit equals x
                ans++; // Increment the counter by 1
            tmp = tmp / 10; // Remove the last digit from the current integer
        }
    }
    cout << ans; // Output the value of counter ans, which is the number of times x appears
    return 0;
}

For detailed information on GESP levels, past exam questions, knowledge expansion, and practice lists, see:

【Top】【GESP】C++ Certification Learning Resources Summary

luogu-” series problems can be evaluated online atLuogu Problem Bank.

bcqm-” series problems can be evaluated online atProgramming Enlightenment Problem Bank.

Leave a Comment