[go: up one dir, main page]

Open In App

Count total number of digits from 1 to n

Last Updated : 03 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Basic
49.73%
3.4K

Given a number n, count the total number of digits required to write all numbers from 1 to n.

Examples: 

Input : 13
Output : 17
Numbers from 1 to 13 are 1, 2, 3, 4, 5, 
6, 7, 8, 9, 10, 11, 12, 13.
So 1 - 9 require 9 digits and 10 - 13 require 8
digits. Hence 9 + 8 = 17 digits are required. 

Input : 4
Output : 4
Numbers are 1, 2, 3, 4 . Hence 4 digits are required.
Recommended Practice

Naive Recursive Method – 
Naive approach to the above problem is to calculate the length of each number from 1 to n, then calculate the sum of the length of each of them. Recursive implementation of the same is – 

C++




#include <bits/stdc++.h>
using namespace std;
 
int findDigits(int n)
{
    if (n == 1)
    {
        return 1;
    }
     
    // Changing number to String
    string s = to_string(n);
     
    // Add length of number to  total_sum
    return s.length() + findDigits(n - 1);
}
 
// Driver code  
int main()
{
    int n = 13;
     
    cout << findDigits(n) << endl;
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07


Java




public class Main {
 
    static int findDigits(int n)
    {
        if (n == 1) {
            return 1;
        }
        // Changing number to String
        String s = String.valueOf(n);
         
        // add length of number to  total_sum
        return s.length() + findDigits(n - 1);
    }
    public static void main(String[] args)
    {
        int n = 13;
        System.out.println(findDigits(n));
    }
}


Python3




def findDigits(N):
 
    if N == 1:
        return 1
 
    # Changing number to string
    s = str(N)
 
    # Add length of number to total_sum
    return len(s) + findDigits(N - 1)
 
# Driver Code
 
# Given N
N = 13
 
# Function call
print(findDigits(N))
 
# This code is contributed by vishu2908


C#




using System;
using System.Collections;
class GFG{
   
static int findDigits(int n)
{
  if (n == 1)
  {
    return 1;
  }
 
  // Changing number to String
  string s = n.ToString();
 
  // add length of number to  total_sum
  return s.Length + findDigits(n - 1);
}
   
// Driver Code
public static void Main(string[] args)
{
  int n = 13;
  Console.Write(findDigits(n));
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
function findDigits(n)
{
    if (n == 1)
    {
        return 1;
    }
     
    // Changing number to String
    let s = n.toString();
     
    // Add length of number to total_sum
    return (s.length + findDigits(n - 1));
}
 
// Driver code
 
    let n = 13;
     
    document.write( findDigits(n) + "<br>");
 
//This code is contributed by Mayank Tyagi
</script>


Output: 

 17

Time Complexity: O(n log n)

Auxiliary Space: O(n log n)

Iterative Method – (Optimized) 
To calculate the number of digits, we have to calculate the total number of digits required to write at ones, tens, hundredths …. places of the number . Consider n = 13, so digits at ones place are 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3 and digits at tens place are 1, 1, 1, 1 . So, total ones place digits from 1 to 13 is basically 13 ( 13 – 0 ) and tens place digits is 4 ( 13 – 9 ) . Let’s take another example n = 234, so digits at unit place are 1 ( 24 times ), 2 ( 24 times ), 3 ( 24 times ), 4 ( 24 times ), 5 ( 23 times ), 6 ( 23 times ), 7 (23 times), 8 ( 23 times ), 9 ( 23 times ), 0 ( 23 times ) hence 23 * 6 + 24 * 4 = 234 . Digits at tens place are 234 – 9 = 225 as from 1 to 234 only 1 – 9 are single digit numbers . And lastly at hundredths place digits are 234 – 99 = 135 as only 1 – 99 are two digit numbers . Hence, total number of digits we have to write are 234 ( 234 – 1 + 1 ) + 225 ( 234 – 10 + 1 ) + 135 ( 234 – 100 + 1 ) = 594 . So, basically we have to decrease 0, 9, 99, 999 … from n to get the number of digits at ones, tens, hundredths, thousandths … places and sum them to get the required result.

Below is the implementation of this approach.

C++




// C++ program to count total number
// of digits we have to write
// from 1 to n
#include <bits/stdc++.h>
using namespace std;
 
int totalDigits(int n)
{
   
    // number_of_digits store total
    // digits we have to write
    int number_of_digits = 0;
 
    // In the loop we are decreasing
    // 0, 9, 99 ... from n till
    // ( n - i + 1 ) is greater than 0
    // and sum them to number_of_digits
    // to get the required sum
    for(int i = 1; i <= n; i *= 10)
        number_of_digits += (n - i + 1);
 
    return number_of_digits;
}
 
// Driver code
int main()
{
    int n = 13;
   
    cout << totalDigits(n) << endl;
   
    return 0;
}


Java




// Java program to count total number of digits
// we have to write from 1 to n
 
public class GFG {
    static int totalDigits(int n)
    {
        // number_of_digits store total
        // digits we have to write
        int number_of_digits = 0;
 
        // In the loop we are decreasing
        // 0, 9, 99 ... from n till
        // ( n - i + 1 ) is greater than 0
        // and sum them to number_of_digits
        // to get the required sum
        for (int i = 1; i <= n; i *= 10)
            number_of_digits += (n - i + 1);
 
        return number_of_digits;
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        int n = 13;
        System.out.println(totalDigits(n));
    }
}


Python3




# Python3 program to count total number
# of digits we have to write from 1 to n
 
def totalDigits(n):
 
    # number_of_digits store total
    # digits we have to write
    number_of_digits = 0;
 
    # In the loop we are decreasing
    # 0, 9, 99 ... from n till
    #( n - i + 1 ) is greater than 0
    # and sum them to number_of_digits
    # to get the required sum
    for i in range(1, n, 10):
        number_of_digits = (number_of_digits +
                                 (n - i + 1));
         
    return number_of_digits;
 
 
# Driver code
n = 13;
s = totalDigits(n) + 1;
print(s);
     
# This code is contributed
# by Shivi_Aggarwal


C#




// C# program to count total number of
// digits we have to write from 1 to n
using System;
 
public class GFG {
 
    static int totalDigits(int n)
    {
 
        // number_of_digits store total
        // digits we have to write
        int number_of_digits = 0;
 
        // In the loop we are decreasing
        // 0, 9, 99 ... from n till
        // ( n - i + 1 ) is greater than 0
        // and sum them to number_of_digits
        // to get the required sum
        for (int i = 1; i <= n; i *= 10)
            number_of_digits += (n - i + 1);
 
        return number_of_digits;
    }
 
    // Driver Method
    public static void Main()
    {
        int n = 13;
 
        Console.WriteLine(totalDigits(n));
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// PHP program to count
// total number of digits
// we have to write from
// 1 to n
 
// Function that return
// total number of digits
function totalDigits($n)
{
     
    // number_of_digits store total
    // digits we have to write
    $number_of_digits = 0;
 
    // In the loop we are decreasing
    // 0, 9, 99 ... from n till
    // ( n - i + 1 ) is greater than 0
    // and sum them to number_of_digits
    // to get the required sum
    for ($i = 1; $i <= $n; $i *= 10)
        $number_of_digits += ($n - $i + 1);
 
    return $number_of_digits;
}
 
    // Driver Code
    $n = 13;
    echo totalDigits($n);
     
// This code is contributed by vt_m.
?>


Javascript




<script>
 
// Javascript program to count total number
// of digits we have to write
// from 1 to n
function totalDigits(n)
{
 
    // number_of_digits store total
    // digits we have to write
    var number_of_digits = 0;
 
    // In the loop we are decreasing
    // 0, 9, 99 ... from n till
    // ( n - i + 1 ) is greater than 0
    // and sum them to number_of_digits
    // to get the required sum
    for(var i = 1; i <= n; i *= 10)
        number_of_digits += (n - i + 1);
 
    return number_of_digits;
}
 
// Driver code
var n = 13;
document.write(totalDigits(n));
 
 
</script>


Output: 

 17

Time Complexity : O(Logn)

 



Similar Reads

Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
Given a number n, we need to count the total number of n digit numbers such that the sum of even digits is 1 more than the sum of odd digits. Here even and odd means positions of digits are like array indexes, for example, the leftmost (or leading) digit is considered as even digit, next to leftmost is considered as odd, and so on. Example: Input:
10 min read
Count of integers in a range which have even number of odd digits and odd number of even digits
Given a range [L, R], the task is to count the numbers which have even number of odd digits and odd number of even digits. For example, 8 has 1 even digit and 0 odd digit - Satisfies the condition since 1 is odd and 0 is even.545 has 1 even digit and 2 odd digits - Satisfies the condition since 1 is odd and 2 is even.4834 has 3 even digits and 1 od
11 min read
Total ways of choosing X men and Y women from a total of M men and W women
Given four integers X, Y, M, and W. The task is to find the number of ways to choose X men and Y women from total M men and W women. Examples: Input: X = 1, Y = 2, M = 1, W = 3 Output: 3 Way 1: Choose the only man and 1st and 2nd women. Way 2: Choose the only man and 2nd and 3rd women. Way 3: Choose the only man and 1st and 3rd women. Input: X = 4,
9 min read
Find the total count of numbers up to N digits in a given base B
Given two integers N and B, the task is to find the count of natural numbers of Base B up to N digits. Examples: Input: N = 2, B = 10 Output: 99 Explanation: 1, 2, 3, 4, 5, 6, 7, 8, 9 are 1 digit Natural numbers of Base 10. 10, 11, 12.........99 are 2 digit Natural numbers of Base 10 So, total = 9 + 90 = 99 Input: N = 2, B = 16 Output: 255 Explanat
4 min read
Total count of sorted numbers upto N digits in range [L, R] (Magnificent necklace combinatorics problem)
Given three integers N, L, and R, the task is to print the total count of ways to form a necklace of at most N pearls such that the values of a pearl lie in the range [L, R] and are in ascending order. Examples: Input: N = 3, L = 6, R = 9Output: 34Explanation:The necklace can be formed in the following ways: The necklaces of length one that can be
8 min read
Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
Given three positive integers N, A, and B. The task is to count the numbers of length N containing only digits A and B and whose sum of digits also contains the digits A and B only. Print the answer modulo 109 + 7.Examples: Input: N = 3, A = 1, B = 3 Output: 1 Possible numbers of length 3 are 113, 131, 111, 333, 311, 331 and so on... But only 111 i
15 min read
Minimum digits to be removed to make either all digits or alternating digits same
Given a numeric string str, the task is to find the minimum number of digits to be removed from the string such that it satisfies either of the below conditions: All the elements of the string are the same.All the elements at even position are same and all the elements at the odd position are same, which means the string is alternating with the equ
7 min read
Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits
Given an array arr[] consisting of queries of the form {L, R}, the task for each query is to count the numbers in the range [L, R] that can be expressed as the sum of its digits raised to the power of count of digits. Examples: Input: arr[][] = {{8, 11}}Output: 2Explanation:From the given range [1, 9], the numbers that can be expressed as the sum o
10 min read
Find the total Number of Digits in (N!)N
Given a number N. The task is to find the total number of Digits in [Tex](N!)^{N} [/Tex]. Examples: Input: N = 3 Output: 3 If N=3, (3!)3=216, So the count of digits is 3 Input: N = 4 Output: 6 Approach: As we know, log(a*b) = log(a) + log(b) Consider, X = log(N!) = log(1*2*3....... * N) = log(1)+log(2)+........ +log(N) Now, we know that the floor v
4 min read
Total number of non-decreasing numbers with n digits
A number is non-decreasing if every digit (except the first one) is greater than or equal to the previous digit. For example, 223, 4455567, 899, are non-decreasing numbers.So, given the number of digits n, you are required to find the count of total non-decreasing numbers with n digits. Examples: Input: n = 1Output: count = 10Input: n = 2Output: co
11 min read
Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
Given a range [L, R] and two positive integers N and M. The task is to count the numbers in the range containing only non-zero digits whose sum of digits is equal to N and the number is divisible by M.Examples: Input: L = 1, R = 100, N = 8, M = 2 Output: 4 Only 8, 26, 44 and 62 are valid numbers Input: L = 1, R = 200, N = 4, M = 11 Output: 2 Only 2
14 min read
Count number of integers in given range with adjacent digits different and sum of digits equal to M
Given integers T, A, and B, the task for this problem is to find numbers in the range [A, B] such that the adjacent digits of the number are different and the sum of digits is equal to T. ( A ? B ? 1018) Examples: Input: T = 5, A = 1, B = 100Output: 6Explanation: 5, 14, 23, 32, 41, and 50 are valid integers that are in between the range 1 to 100 an
15+ min read
Find smallest number with given number of digits and sum of digits under given constraints
Given two integers S and D, the task is to find the number having D number of digits and the sum of its digits as S such that the difference between the maximum and the minimum digit in the number is as minimum as possible. If multiple such numbers are possible, print the smallest number.Examples: Input: S = 25, D = 4 Output: 6667 The difference be
7 min read
Number formed by deleting digits such that sum of the digits becomes even and the number odd
Given a non-negative number N, the task is to convert the number by deleting some digits of the number, such that the sum of the digits becomes even but the number is odd. In case there is no possible number, then print -1.Note: There can be multiple numbers possible for a given N.Examples: Input: N = 18720 Output: 17 Explanation: After Deleting 8,
5 min read
Find second smallest number from sum of digits and number of digits
Given the sum of digits as S and the number of digits as D, the task is to find the second smallest number Examples: Input: S = 9, D = 2Output: 27Explanation: 18 is the smallest number possible with sum = 9 and total digits = 2, Whereas the second smallest is 27. Input: S = 16, D = 3Output: 178Explanation: 169 is the smallest number possible with s
8 min read
Number of digits in the nth number made of given four digits
Find the number of digits in the nth number constructed by using 6, 1, 4, and 9 as the only digits in the ascending order. First few numbers constructed by using only 6, 1, 4, and 9 as digits in ascending order would be: 1, 6, 4, 9, 11, 14, 16, 19, 41, 44, 46, 49, 61, 64, 66, 69, 91, 94, 96, 99, 111, 114, 116, 119 and so on. Examples: Input : 6Outp
13 min read
Find smallest number with given number of digits and sum of digits
How to find the smallest number with given digit sum s and number of digits d? Examples : Input : s = 9, d = 2 Output : 18 There are many other possible numbers like 45, 54, 90, etc with sum of digits as 9 and number of digits as 2. The smallest of them is 18. Input : s = 20, d = 3 Output : 299 Recommended PracticeSmallest numberTry It! A Simple So
9 min read
Find the Largest number with given number of digits and sum of digits
Given an integer s and d, The task is to find the largest number with given digit sum s and the number of digits d. Examples: Input: s = 9, d = 2Output: 90 Input: s = 20, d = 3Output: 992 Recommended PracticeLargest number possibleTry It! Naive Approach: Consider all m digit numbers and keep a max variable to store the maximum number with m digits
13 min read
Total numbers with no repeated digits in a range
Given a range [Tex]L, R [/Tex]find total such numbers in the given range such that they have no repeated digits. For example: 12 has no repeated digit. 22 has repeated digit. 102, 194 and 213 have no repeated digit. 212, 171 and 4004 have repeated digits. Examples: Input : 10 12 Output : 2 Explanation : In the given range 10 and 12 have no repeated
15+ min read
Count N-digit numbers whose digits does not exceed absolute difference of the two previous digits
Given an integer N, the task is to count the number of N-digit numbers such that each digit, except the first and second digits, is less than or equal to the absolute difference of the previous two digits. Examples: Input: N = 1Output: 10Explanation: All the numbers from [0 - 9] are valid because the number of digits is 1. Input : N = 3Output : 375
9 min read
Count numbers in given range such that sum of even digits is greater than sum of odd digits
Given two integers L and R denoting a range [L, R]. The task is to find the total count of numbers in the given range [L,R] whose sum of even digits is greater than the sum of odd digits. Examples: Input : L=2 R=10 Output : 4 Numbers having the property that sum of even digits is greater than sum of odd digits are: 2, 4, 6, 8 Input : L=2 R=17 Outpu
14 min read
Count of numbers upto N digits formed using digits 0 to K-1 without any adjacent 0s
Given two integers N and K, the task is to count the numbers up to N digits such that no two zeros are adjacents and the range of digits are from 0 to K-1.Examples: Input: N = 2, K = 3 Output: 8 Explanation: There are 8 such numbers such that digits are from 0 to 2 only, without any adjacent 0s: {1, 2, 10, 11, 12, 20, 21, 22}Input: N = 3, K = 3 Out
12 min read
Count numbers from given range having odd digits at odd places and even digits at even places
Given two integers L and R, the task is to count numbers from the range [L, R] having odd digits at odd positions and even digits at even positions respectively. Examples: Input: L = 3, R = 25Output: 9Explanation: The numbers satisfying the conditions are 3, 5, 7, 9, 10, 12, 14, 16 and 18. Input: L = 128, R = 162Output: 7Explanation: The numbers sa
15+ min read
Count of numbers in range [L, R] having sum of digits of its square equal to square of sum of digits
Given two integers L and R, the task is to find the count of numbers in range [L, R] such that the sum of digits of its square is equal to the square of sum of its digits, Example: Input: L = 22, R = 22Output: 1Explanation: 22 is only valid number in this range as sum of digits of its square = S(22*22) = S(484) = 16 and square of sum of its digits
11 min read
Count numbers in range whose sum of digits is divisible by XOR of digits
Given integers L and R, the task for this problem is to find a number of integers in the range L to R whose sum of digits is divisible by bitwise XOR of digits. print the answer. ( L <= R <= 1018) Note: Bitwise XOR sum zero never divides any other number. Examples: Input: L = 10, R = 15Output: 4Explanation: Number 10 : digitSum = 1 + 0 = 1, x
15+ min read
Count N-digits numbers made up of even and prime digits at odd and even positions respectively
Given a positive integer N, the task is to find the number of integers of N digits having even digits at odd indices and prime digits at even indices. Examples: Input: N = 2Output: 20Explanation:Following are the possible number of 2-digits satisfying the given criteria {20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 50, 52, 54, 56, 58, 70, 72, 74, 76, 78
12 min read
Count the total number of squares that can be visited by Bishop in one move
Given the position of a Bishop on an 8 * 8 chessboard, the task is to count the total number of squares that can be visited by the Bishop in one move. The position of the Bishop is denoted using row and column number of the chessboard. Examples: Input: Row = 4, Column = 4 Output: 13 Input: Row = 1, Column = 1 Output: 7 Approach: In the game of ches
5 min read
Count total number of even sum sequences
Given an integer N, the task is to count all possible sequences of length N such that all the elements of the sequence are from the range [1, N] and the sum of the elements of the sequence is even. As the answer could be very large so print the answer modulo 109 + 7.Examples: Input: N = 3 Output: 13 All possible sequences of length 3 will be (1, 1,
12 min read
Count the total number of triangles after Nth operation
Given an equilateral triangle, the task is to compute the total number of triangles after performing the following operation N times. For every operation, the uncolored triangles are taken and divided into 4 equal equilateral triangles. Every inverted triangle formed is colored. Refer to the below figure for more details. For N=1 the triangle forme
3 min read
Count total bits in a number
Given a positive number n, count total bit in it.Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 Method 1 (Using Log) The log2(n) logarithm in base 2 of n, which is the exponent to which 2 is raised to get n only integer and we add 1 find total bit in a number in log(n) time. C/C++
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg