모든 챌린지
쉬움 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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

아직 통과한 풀이가 없습니다. 풀어서 1위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.