Cuente el número total de dígitos de 1 a n

Dado un número n, cuente el número total de dígitos necesarios para escribir todos los números del 1 al n.

Ejemplos: 

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.

Método recursivo 
ingenuo: el enfoque ingenuo del problema anterior es calcular la longitud de cada número de 1 a n, luego calcular la suma de la longitud de cada uno de ellos. La implementación recursiva de la misma es – 

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>

Producción: 

 17

Método Iterativo – (Optimizado) 
Para calcular el número de dígitos, tenemos que calcular el número total de dígitos necesarios para escribir en unidades, decenas, centésimas…. lugares del numero. Considere n = 13, entonces los dígitos en el lugar de las unidades son 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3 y los dígitos en el lugar de las decenas son 1, 1, 1, 1. Por lo tanto, el total de dígitos de las unidades del 1 al 13 es básicamente 13 (13 – 0) y los dígitos de las decenas son 4 (13 – 9). Tomemos otro ejemplo n = 234, por lo que los dígitos en el lugar de la unidad son 1 (24 veces), 2 (24 veces), 3 (24 veces), 4 (24 veces), 5 (23 veces), 6 (23 veces), 7 (23 veces), 8 (23 veces), 9 (23 veces), 0 (23 veces), por lo tanto, 23 * 6 + 24 * 4 = 234. Los dígitos en el lugar de las decenas son 234 – 9 = 225 ya que del 1 al 234 solo 1 – 9 son números de un solo dígito. Y, por último, en el lugar de las centésimas, los dígitos son 234 – 99 = 135, ya que solo 1 – 99 son números de dos dígitos. Por lo tanto, el número total de dígitos que tenemos que escribir es 234 (234 – 1 + 1) + 225 (234 – 10 + 1) + 135 (234 – 100 + 1) = 594. Entonces, básicamente tenemos quedisminuya 0, 9, 99, 999… de n para obtener el número de dígitos en unidades, decenas, centésimas, milésimas… lugares y súmelos para obtener el resultado requerido .

A continuación se muestra la implementación de este enfoque.

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>

Producción: 

 17

Complejidad de tiempo: O (Iniciar sesión)

Este artículo es una contribución de Surya Priy . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *