Contar números con el mismo primer y último dígito

Dado un intervalo, la tarea es contar números que tienen el mismo primer y último dígito. Por ejemplo, 1 23 1 tiene el mismo primer y último dígito. 
 

Ejemplos: 

Input  : start = 7,  end : 68
Output : 9
Number with same first and last digits are,
7 8 9 11 22 33 44 55 66.

Input  : start = 5,  end : 40
Output : 8

Consideremos primero los siguientes ejemplos para comprender el enfoque. 

From 120 to 130, only 121 has same starting and ending digit
From 440 to 450, only 444 has same starting and ending digit
From 1050 to 1060, only 1051 has same starting and ending digit

De los ejemplos anteriores, podemos observar que en cada rango de diez números tenemos solo un número que tiene la propiedad dada excepto del 1 al 10 que tiene 9 números (todos números de un dígito) que tienen el mismo dígito inicial y final. 
Usando la propiedad anterior podemos resolver el problema dado, primero dividimos el intervalo dado en dos partes, es decir, si el intervalo es de l a r, lo dividimos en 1 a l y 1 a r, nuestra respuesta se obtiene restando el resultado de la primera consulta de segunda consulta. 
Ahora nos queda encontrar el conteo de números con la propiedad dada en el rango de 1 a x, para esto, dividimos x por 10, lo que da el número de 10 tramos. Agregamos 9 al lapso para tener en cuenta números de un dígito. Si el último dígito de x es más pequeño que el primer dígito de x, entonces se debe disminuir 1 en la respuesta final para descartar el último número de diez intervalos porque ese número está fuera de rango. 
 

C++

// C++ program to get count of numbers with
// same start and end digit in an interval
#include <bits/stdc++.h>
using namespace std;
 
// Utility method to get first digit of x
int getFirstDigit(int x)
{
    while (x >= 10)
        x /= 10;
    return x;
}
 
// method to return count of numbers with same
// starting and ending digit from 1 upto x
int getCountWithSameStartAndEndFrom1(int x)
{
    if (x < 10)
        return x;
 
    // get ten-spans from 1 to x
    int tens = x / 10;
 
    // add 9 to consider all 1 digit numbers
    int res = tens + 9;
 
    // Find first and last digits
    int firstDigit = getFirstDigit(x);
    int lastDigit = x % 10;
 
    // If last digit is smaller than first digit
    // then decrease count by 1
    if (lastDigit < firstDigit)
        res--;
 
    return res;
}
 
// Method to return count of numbers with same starting
// and ending digit between start and end
int getCountWithSameStartAndEnd(int start, int end)
{
    return getCountWithSameStartAndEndFrom1(end)
    - getCountWithSameStartAndEndFrom1(start - 1);
}
 
// Driver code to test above methods
int main()
{
    int start = 5, end = 40;
 
    cout << getCountWithSameStartAndEnd(start, end);
 
    return 0;
}

C

// C program to get count of numbers with
// same start and end digit in an interval
#include <stdio.h>
// Utility method to get first digit of x
int getFirstDigit(int x)
{
    while (x >= 10)
        x /= 10;
    return x;
}
 
// method to return count of numbers with same
// starting and ending digit from 1 upto x
int getCountWithSameStartAndEndFrom1(int x)
{
    if (x < 10)
        return x;
 
    // get ten-spans from 1 to x
    int tens = x / 10;
 
    // add 9 to consider all 1 digit numbers
    int res = tens + 9;
 
    // Find first and last digits
    int firstDigit = getFirstDigit(x);
    int lastDigit = x % 10;
 
    // If last digit is smaller than first digit
    // then decrease count by 1
    if (lastDigit < firstDigit)
        res--;
 
    return res;
}
 
// Method to return count of numbers with same starting
// and ending digit between start and end
int getCountWithSameStartAndEnd(int start, int end)
{
    return getCountWithSameStartAndEndFrom1(end)
    - getCountWithSameStartAndEndFrom1(start - 1);
}
 
// Driver code to test above methods
int main()
{
    int start = 5, end = 40;
 
    printf("%d",getCountWithSameStartAndEnd(start, end));
 
    return 0;
}
 
// This code is contributed by allwink45.

Java

// Java program to get count of numbers with
// same start and end digit in an interval
import java.util.*;
 
class Digits {
    // Utility method to get first digit of x
    public static int getFirstDigit(int x)
    {
        while (x >= 10)
            x /= 10;
        return x;
    }
 
    // method to return count of numbers with same
    // starting and ending digit from 1 upto x
    public static int getCountWithSameStartAndEndFrom1(int x)
    {
        if (x < 10)
            return x;
 
        // get ten-spans from 1 to x
        int tens = x / 10;
 
        // add 9 to consider all 1 digit numbers
        int res = tens + 9;
 
        // Find first and last digits
        int firstDigit = getFirstDigit(x);
        int lastDigit = x % 10;
 
        // If last digit is smaller than first
        // digit then decrease count by 1
        if (lastDigit < firstDigit)
            res--;
 
        return res;
    }
 
    // Method to return count of numbers with same
    // starting and ending digit between start and end
    public static int getCountWithSameStartAndEnd(int start,
                                                  int end)
    {
        return getCountWithSameStartAndEndFrom1(end)
        - getCountWithSameStartAndEndFrom1(start - 1);
    }
 
    // driver code
    public static void main(String[] args)
    {
        int start = 5, end = 40;
        System.out.print(getCountWithSameStartAndEnd(start,
                                                     end));
    }
}
 
// This code is contributed by rishabh_jain

Python3

# Python3 program to get count of numbers with
# same start and end digit in an interval
 
# Utility method to get first digit of x
def getFirstDigit(x) :
    while (x >= 10) :
        x //= 10
    return x
 
# method to return count of numbers with same
# starting and ending digit from 1 upto x
def getCountWithSameStartAndEndFrom1(x) :
    if (x < 10):
        return x
 
    # get ten-spans from 1 to x
    tens = x // 10
 
    # add 9 to consider all 1 digit numbers
    res = tens + 9
 
    # Find first and last digits
    firstDigit = getFirstDigit(x)
    lastDigit = x % 10
 
    # If last digit is smaller than first digit
    # then decrease count by 1
    if (lastDigit < firstDigit) :
        res = res - 1
 
    return res
 
# Method to return count of numbers with same starting
# and ending digit between start and end
def getCountWithSameStartAndEnd(start, end) :
    return (getCountWithSameStartAndEndFrom1(end) -
           getCountWithSameStartAndEndFrom1(start - 1))
 
# Driver Code
start = 5
end = 40
print(getCountWithSameStartAndEnd(start, end))
 
# This code is contributed by rishabh_jain
# Improved by cidacoder

C#

// C# program to get count of numbers with
// same start and end digit in an interval
using System;
 
class GFG {
     
    // Utility method to get first digit
    // of x
    public static int getFirstDigit(int x)
    {
        while (x >= 10)
            x /= 10;
             
        return x;
    }
 
    // method to return count of numbers
    // with same starting and ending digit
    // from 1 upto x
    public static int getCountWithSameStartAndEndFrom1(
                                                  int x)
    {
         
        if (x < 10)
            return x;
 
        // get ten-spans from 1 to x
        int tens = x / 10;
 
        // add 9 to consider all 1 digit
        // numbers
        int res = tens + 9;
 
        // Find first and last digits
        int firstDigit = getFirstDigit(x);
        int lastDigit = x % 10;
 
        // If last digit is smaller than
        // first digit then decrease count
        // by 1
        if (lastDigit < firstDigit)
            res--;
 
        return res;
    }
 
    // Method to return count of numbers
    // with same starting and ending digit
    // between start and end
    public static int getCountWithSameStartAndEnd(
                                 int start, int end)
    {
        return getCountWithSameStartAndEndFrom1(end)
        - getCountWithSameStartAndEndFrom1(start - 1);
    }
 
    // driver code
    public static void Main()
    {
        int start = 5, end = 40;
         
        Console.Write(getCountWithSameStartAndEnd(start,
                                                end));
    }
}
 
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to get count of numbers with
// same start and end digit in an interval
 
// method to get first digit of x
function getFirstDigit($x)
{
    while ($x >= 10)
        $x /= 10;
    return $x;
}
 
// method to return count
// of numbers with same
// starting and ending
// digit from 1 upto x
function getCountWithSameStartAndEndFrom1($x)
{
    if ($x < 10)
        return $x;
 
    // get ten-spans from 1 to x
    $tens = $x / 10;
 
    // add 9 to consider all
    // 1 digit numbers
    $res = $tens + 9;
 
    // Find first and last digits
    $firstDigit = getFirstDigit($x);
    $lastDigit = $x % 10;
 
    // If last digit is smaller
    // than first digit
    // then decrease count by 1
    if ($lastDigit < $firstDigit)
        $res--;
 
    return $res;
}
 
// Method to return count of
// numbers with same starting
// and ending digit between
// start and end
function getCountWithSameStartAndEnd($start, $end)
{
    return getCountWithSameStartAndEndFrom1($end)
          - getCountWithSameStartAndEndFrom1($start - 1);
}
 
    // Driver Code
    $start = 5;
    $end = 40;
    echo getCountWithSameStartAndEnd($start, $end);
 
// This code is contributed by nitin mittal.
?>

Javascript

<script>
 
// JavaScript program to get count of numbers with
// same start and end digit in an interval
 
    // Utility method to get first digit of x
    function getFirstDigit(x)
    {
        while (x >= 10)
            x /= 10;
        return x;
    }
   
    // method to return count of numbers with same
    // starting and ending digit from 1 upto x
    function getCountWithSameStartAndEndFrom1(x)
    {
        if (x < 10)
            return x;
   
        // get ten-spans from 1 to x
        let tens = x / 10;
   
        // add 9 to consider all 1 digit numbers
        let res = tens + 9;
   
        // Find first and last digits
        let firstDigit = getFirstDigit(x);
        let lastDigit = x % 10;
   
        // If last digit is smaller than first
        // digit then decrease count by 1
        if (lastDigit < firstDigit)
            res--;
   
        return res;
    }
   
    // Method to return count of numbers with same
    // starting and ending digit between start and end
    function getCountWithSameStartAndEnd(start,
                                               end)
    {
        return getCountWithSameStartAndEndFrom1(end)
        - getCountWithSameStartAndEndFrom1(start - 1);
    }
   
 
// Driver code
      let start = 5, end = 40;
      document.write(getCountWithSameStartAndEnd(start,
                                                     end)); 
</script>

Producción: 

8

Complejidad de tiempo: O (log 10 N)

Espacio auxiliar: O(1)
Este artículo es una contribución de Utkarsh Trivedi . 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 *