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

  • برمجة سي بلس بلس
  • برمجة

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 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

الأجوبة

#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;    
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...