문제
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
예시
입력:
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.
입력:
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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.