Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
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 digit 1 pressent 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;

int count_digit_one(int n) {
        int ctr = 0;
        for (int i = 1; i <= n; i *= 10) {
            int a = n / i;
            int b = n % i;
            ctr += (a + 8) / 10 * i;
            if (1 == a % 10) {
                ctr += b + 1;
            }
        }
        return ctr;
    }

int main() {
	int n = 10;
    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?