ReverseUnnaturalBaseConversion
SRM 342 · 2007-03-14 · by Kawigi
Problem Statement
It is common in modern written languages to express numbers in base 10, where the digits 0-9 are used to express values as sums of powers of 10. For instance, the number written as 12345 in base 10 refers to the sum 1*104 + 2*103 + 3*102 + 4*101 + 5*100. It is also common in various applications to represent numbers in other number bases (such as base 2, which is how computers represent numbers). Additionally, a '-' character preceding a number denotes that it is negative.
Consider for a minute what it would mean to express a number in base -10. The number written as 12345 in base -10 refers to the sum 1*(-10)4 + 2*(-10)3 + 3*(-10)2 + 4*(-10)1 + 5*(-10)0. Note that the odd powers of ten are negative, and the value of that sum is 10000 - 2000 + 300 - 40 + 5, which comes out to 8265 in base +10. It turns out that there is a unique way of representing any integer in negative bases (as long as the absolute value of the base is at least 2). The really interesting thing about using negative number bases is that the '-' sign isn't needed to represent negative numbers - -1 can be expressed as 19 in base -10, -2 is 18, and so on.
For this problem, write a program that converts a number x to base b, and returns this representation as a
Notes
- There will always be a unique answer for any valid input.
Constraints
- The absolute value of b will be between 2 and 10, inclusive.
- x will be between -1000000000 and 1000000000, inclusive.
12345 10 Returns: "12345"
Conversion into base 10 should look natural.
8265 -10 Returns: "12345"
The other example from the problem statement.
1001 -2 Returns: "10000111001"
-52 -2 Returns: "11011100"
-38 4 Returns: "-212"
Submissions are judged against all 150 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class ReverseUnnaturalBaseConversion with a public method string convertToBase(int x, int b) · 150 test cases · 2 s / 256 MB per case