모든 챌린지
쉬움 0명 해결 정답률 0%

Base Converter

Convert a number written in one base (2 to 36) to another base.

배우게 될 내용

  • Read digits in any base into a number
  • Write a number in any base with remainders
  • Map digit values to characters and back

문제

번역본 보기

In base b a number is written with the digits 0 to b − 1, where the letters A to Z stand for the digit values 10 to 35. So FF in base 16 is 255, which is 377 in base 8 and 11111111 in base 2. Convert digits, written in from_base, to the same number written in to_base.

Implement base_converter(digits, from_base, to_base).

Input

digits: The number in from_base: a non-empty string of digits and uppercase letters, each smaller than from_base. It may have leading zeros.

from_base: The base of the input.

to_base: The base of the result.

Output

Return the number in to_base using 0-9 and uppercase A-Z, with no leading zeros. Zero is returned as "0".

제약 조건

2 ≤ from_base, to_base ≤ 36

The value of the number is at most 10^18.

예시

예시 1
입력:
digits = "FF"
from_base = 16
to_base = 8

예상 출력:
expected = "377"
입력:
std::string digits = "FF";
long long from_base = 16;
long long to_base = 8;

예상 출력:
std::string expected = "377";
입력:
string digits = "FF";
long from_base = 16;
long to_base = 8;

예상 출력:
string expected = "377";

설명

FF is 15 × 16 + 15 = 255, and 255 = 3 × 64 + 7 × 8 + 7, so the answer is "377".

예시 2
입력:
digits = "1010"
from_base = 2
to_base = 36

예상 출력:
expected = "A"
입력:
std::string digits = "1010";
long long from_base = 2;
long long to_base = 36;

예상 출력:
std::string expected = "A";
입력:
string digits = "1010";
long from_base = 2;
long to_base = 36;

예상 출력:
string expected = "A";

설명

1010 in binary is 10, which is the single digit "A" in base 36.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

Go through the input left to right, multiplying the running value by from_base and adding each digit.

힌트 2

To write the result, take remainders of division by to_base; they come out last digit first.

힌트 3

Treat zero as a special case so the output is "0" rather than empty.

예상 복잡도

O(L) time, O(L) extra space, where L is the number of digits

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

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

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

다른 사람의 풀이 보기

커뮤니티 솔루션

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