w3resource

C++ Exercises: Count the total number of digit 1 pressent in all positive numbers less than or equal to a given integer

C++ Math: Exercise-25 with Solution

Write a C++ program to count the total number of digits 1 present in all positive numbers less than or equal to a given integer.

Sample Input: n = 10
Sample Output: Number of digit 1 present in all +ve numbers less than or equal to 10 is 2
Sample Input: n = 19
Sample Output: Number of digit 1 present in all +ve numbers less than or equal to 19 is 12

Sample Solution:

C++ Code :

#include <iostream>
#include <cmath>

using namespace std;

// Function to count the occurrence of digit 1 in positive integers up to 'n'
int count_digit_one(int n) {
    int ctr = 0; // Initialize a counter for digit '1' occurrences

    // Iterate through each digit place, starting from the ones place
    for (int i = 1; i <= n; i *= 10) {
        int a = n / i; // Get the quotient when dividing 'n' by 'i'
        int b = n % i; // Get the remainder when dividing 'n' by 'i'

        // Calculate the occurrences of digit '1' at each digit place and accumulate them
        ctr += (a + 8) / 10 * i;

        // Check if the current digit is '1' and add the count accordingly
        if (1 == a % 10) {
            ctr += b + 1;
        }
    }
    return ctr; // Return the total count of digit '1' occurrences
}

int main() {
    int n = 10;
    // Display the count of digit '1' present in all positive numbers less than or equal to 'n'
    cout << "Number of digit 1 present in all +ve numbers less than or equal to " << n << " is " << count_digit_one(n);

    n = 19;
    cout << "\nNumber of digit 1 present in all +ve numbers less than or equal to " << n << " is " << count_digit_one(n);

    n = 100;
    cout << "\nNumber of digit 1 present in all +ve numbers less than or equal to " << n << " is " << count_digit_one(n);

    return 0;    
}

Sample Output:

Number of digit 1 present in all +ve numbers less than or equal to 10 is 2
Number of digit 1 present in all +ve numbers less than or equal to 19 is 12
Number of digit 1 present in all +ve numbers less than or equal to 100 is 21

Flowchart:

Flowchart: Count the total number of digit 1 pressent in all positive numbers less than or equal to a given integer

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to count the prime numbers less than a given positive number.
Next: Write a C++ program to find the missing number in a given array of integers taken from the sequence 0, 1, 2, 3, ...,n.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/math/cpp-math-exercise-25.php