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

Double-Base Palindromes

Add up the numbers that read the same both ways in base 10 and in a second base.

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

  • Convert a number to any base
  • Check whether a sequence is a palindrome
  • Combine two conditions cheaply

โจทย์

ดูฉบับแปล

A palindrome reads the same forwards and backwards. 33 is a palindrome in base 10, and in base 2 it is 100001, a palindrome again. Add up every number from 1 to limit that is a palindrome both in base 10 and in base base. Numbers are written without leading zeros.

Implement double_base_palindromes(limit, base).

Input

limit: The largest number to check.

base: The second base.

Output

Return the sum of all such numbers.

เงื่อนไข

1 ≤ limit ≤ 100,000; 2 ≤ base ≤ 16

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
limit = 10
base = 2

ผลลัพธ์ที่คาดหวัง:
expected = 25
อินพุต:
long long limit = 10;
long long base = 2;

ผลลัพธ์ที่คาดหวัง:
long long expected = 25;
อินพุต:
long limit = 10;
long base = 2;

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

คำอธิบาย

1, 3, 5, 7 and 9 are 1, 11, 101, 111 and 1001 in base 2, all palindromes; 2, 4, 6 and 8 are not. Sum 25.

ตัวอย่างที่ 2
อินพุต:
limit = 50
base = 3

ผลลัพธ์ที่คาดหวัง:
expected = 15
อินพุต:
long long limit = 50;
long long base = 3;

ผลลัพธ์ที่คาดหวัง:
long long expected = 15;
อินพุต:
long limit = 50;
long base = 3;

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

คำอธิบาย

In base 3: 1, 2, 4 (11) and 8 (22) qualify, while 33 is 1020 and 44 is 1122. Sum 15.

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

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

คำใบ้ 1

Repeated division by the base gives the digits from last to first.

คำใบ้ 2

A palindrome check compares the digit list with its reverse.

คำใบ้ 3

Check base 10 first: few numbers pass it, so the second conversion is rarely needed.

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

O(limit × log limit) time, O(log limit) extra space

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

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

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

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

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

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