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
- برمجة سي بلس بلس
- برمجة
- 2021-05-13
- MarwaMohammed
الأجوبة
#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;
}
أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال