ยาก 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Count Numbers With Distinct Neighbors

Count range values whose adjacent decimal digits are never equal.

สิ่งที่คุณจะได้เรียนรู้

  • 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)

โจทย์

ดูฉบับแปล

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.

เงื่อนไข

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

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
left = 10
right = 15

ผลลัพธ์ที่คาดหวัง:
expected = 5
อินพุต:
long long left = 10;
long long right = 15;

ผลลัพธ์ที่คาดหวัง:
long long expected = 5;
อินพุต:
long left = 10;
long right = 15;

ผลลัพธ์ที่คาดหวัง:
long expected = 5;

คำอธิบาย

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

ตัวอย่างที่ 2
อินพุต:
left = 0
right = 9

ผลลัพธ์ที่คาดหวัง:
expected = 10
อินพุต:
long long left = 0;
long long right = 9;

ผลลัพธ์ที่คาดหวัง:
long long expected = 10;
อินพุต:
long left = 0;
long right = 9;

ผลลัพธ์ที่คาดหวัง:
long expected = 10;

คำอธิบาย

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

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

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

คำใบ้ 2

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

คำใบ้ 3

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

ความซับซ้อนที่คาดหวัง

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

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก