Volver a los desafíos
Difícil 0 resueltos 0% de aceptación

Count Numbers With Distinct Neighbors

Count range values whose adjacent decimal digits are never equal.

Lo que aprenderás

  • Count numbers up to a limit digit by digit
  • Track the previous digit and tight bounds
  • Answer a range as f(b) - f(a - 1)

Problema

Ver traducción

Count integers from left through right, including both endpoints, that have no equal neighboring digits. Use their usual decimal writing with no leading zeroes. Zero and all other single-digit numbers qualify.

Implement counting_numbers(left, right).

Input

left: The first allowed value.

right: The last allowed value.

Output

Return how many values satisfy the rule.

Restricciones

0 ≤ left ≤ right ≤ 10¹⁸. The range may be too large to inspect each integer individually.

Ejemplos

Ejemplo 1
Entrada:
left = 10
right = 15

Salida esperada:
expected = 5
Entrada:
long long left = 10;
long long right = 15;

Salida esperada:
long long expected = 5;
Entrada:
long left = 10;
long right = 15;

Salida esperada:
long expected = 5;

Explicación

Only 11 has equal neighboring digits. The other five numbers qualify.

Ejemplo 2
Entrada:
left = 0
right = 9

Salida esperada:
expected = 10
Entrada:
long long left = 0;
long long right = 9;

Salida esperada:
long long expected = 10;
Entrada:
long left = 0;
long right = 9;

Salida esperada:
long expected = 10;

Explicación

All ten values have just one digit and therefore no equal neighbors.

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

Count valid numbers up to each endpoint, then subtract to get the range answer.

Pista 2

Digit DP fits because validity depends on adjacent digits and whether you have started the number.

Pista 3

Leading zeros need special handling so that shorter numbers are counted correctly.

Complejidad esperada

O(k * 10 * states) time, O(k * states) extra space

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.