Tutte le sfide
Facile 0 risolte 0% di accettazione

Double-Base Palindromes

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

Esempio 1
Input:
limit = 10
base = 2

Output atteso:
expected = 25
Input:
long long limit = 10;
long long base = 2;

Output atteso:
long long expected = 25;
Input:
long limit = 10;
long base = 2;

Output atteso:
long expected = 25;

Spiegazione

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.

Esempio 2
Input:
limit = 50
base = 3

Output atteso:
expected = 15
Input:
long long limit = 50;
long long base = 3;

Output atteso:
long long expected = 15;
Input:
long limit = 50;
long base = 3;

Output atteso:
long expected = 15;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

A palindrome check compares the digit list with its reverse.

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.