Все задачи
Легко Решено: 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. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

Принятых решений пока нет. Решите задачу и займите первое место.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.