Sponsored
Sponsored
In this approach, we iterate through each number from 0 to n. For each number, we count the number of times digit 1 appears. Although this approach is simple, it's not optimal for large values of n due to its high time complexity.
Time Complexity: O(n * log10(n)), as it checks each digit of each number from 1 to n.
Space Complexity: O(1), as it uses a fixed amount of space.
1function countDigitOne(n) {
2 let count = 0;
3 for (let i = 1; i <= n; i++) {
4 let num = i;
5 while (num > 0) {
6 if (num % 10 === 1) count++;
7 num = Math.floor(num / 10);
8 }
9 }
10 return count;
11}
12
13const n = 13;
14console.log(countDigitOne(n));
This JavaScript function counts ones by iterating through each number and examining each digit.
This optimized approach examines digit positions and calculates how many times 1 appears at each position up to n. It leverages the structure of numbers and is more efficient for large values of n.
Time Complexity: O(log10(n)), as it iterates digit by digit.
Space Complexity: O(1), as it uses a fixed amount of space.
1def
In this Python solution, for each digit in n, the number of occurrences of '1' at that digit position is calculated and aggregated to provide the final count.