Weird Numbers
InterviewTime limit1sMemory limit128 MB
Convert numbers between decimal and a given negative base representation, in both directions, for multiple queries until an end marker.
- Level
Medium4 of 10
- Topics
- Math, Implementation, Simulation
- Solved
- No attempts yet
Problem
Binary numbers form the principal basis of computer science. Most people have heard of other systems, such as ternary, octal, or hexadecimal, and know how to use them and convert numbers between them. But did you know that the base (radix) of a number system can also be negative? A university lecturer recently encountered negabinary numbers and other systems with a negative base. Will you help convert numbers to and from these systems?
A number written in a system with a positive base is a string of digits between and inclusive. A digit at position (positions are counted from right to left, starting at zero) represents a value of : the digit is multiplied by , and the values of all positions are summed. For example, in the octal system () the number has the value
With a negative radix the principle is the same: a digit at position has a value of . For example, the number in base equals
One big advantage of a negative base is that no minus sign is needed to write negative numbers. Here are some examples for the negabinary system ():
When no leading zeros are allowed, the representation of any integer in a negative base is unique; the only number that may start with the digit 0 is zero itself.
Input
The input contains several conversions, one per line.
A conversion from decimal to a negative-base system begins with the lowercase word to, immediately followed (no space) by a minus sign and the base , then one space and a decimal number . For example, to-2 10 asks for written in base .
A conversion to decimal begins with the lowercase word from, immediately followed by a minus sign and the base , then one space and a number written in base . For example, from-2 1010 asks for the decimal value of read in base .
The input ends with a line containing the lowercase word end. All numbers satisfy and (in decimal).
Output
For each conversion, print one number on its own line. If the conversion started from decimal, print the same value written in base . If the conversion was to decimal, print the decimal value.
Neither the input nor the output numbers contain leading zeros. A minus sign - may appear only with a negative number written in decimal; any non-negative number, or any number written in a negative base, must not begin with one.