ง่าย 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก