TopCoder problem "ReverseUnnaturalBaseConversion" used in SRM 342 (Division II Level Three)



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 String. The '-' character should be used to denote negative numbers in positive bases, but shouldn't ever be present in numbers in negative bases. The return value should have no unnecessary leading zeros.

 

Definition

    
Class:ReverseUnnaturalBaseConversion
Method:convertToBase
Parameters:int, int
Returns:String
Method signature:String convertToBase(int x, int b)
(be sure your method is public)
    
 

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.
 

Examples

0)
    
12345
10
Returns: "12345"
Conversion into base 10 should look natural.
1)
    
8265
-10
Returns: "12345"
The other example from the problem statement.
2)
    
1001
-2
Returns: "10000111001"
3)
    
-52
-2
Returns: "11011100"
4)
    
-38
4
Returns: "-212"
5)
    
-123456789
-7
Returns: "3031330536"
6)
    
0
2
Returns: "0"

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7413

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10666&pm=7413

Writer:

Kawigi

Testers:

PabloGilberto , brett1479 , Cosmin.ro , Olexiy

Problem categories:

Math