簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。