How to solve ‘bijectiveBase10’ in CodeFights

The Problem:

Consider a numeral system similar to base-10 numeral system with the only difference that it does not use a digit to represent zero; instead it has a digit to represent ten, such as A. It is called bijective base-10 system. For example, numbers that do not contain zeros in base-10 system remain the same when converted to bijective base-10 system.

Given a positive integer in base-10 system, return its representation in bijective base-10 system.

Example

  • For a = 12345, the output should be
    bijectiveBase10(a) = "12345";
  • For a = 10, the output should be
    bijectiveBase10(a) = "A";
  • For a = 100, the output should be
    bijectiveBase10(a) = "9A".

    100 = 10 * 9 + 10 -> "9A".

  • For a = 2010, the output should be
    bijectiveBase10(a) = "19AA".

    2010 = 1 * 103 + 9 * 102 + 10 * 10 + 10 -> "19AA".

Input/Output

  • [time limit] 4000ms (py)
  • [input] integer a

    A positive integer.

    Guaranteed constraints:
    10 ≤ a ≤ 6 · 108.

  • [output] string

    The string representation of a in bijective base-10 system.

 

The Solution:

def bijectiveBase10(a):
    if '0' not in `a`:
        return `a`
    r=""
    while a>0:
        if a%10==0:
            a-=10
            r+="A"
        else:
            r+=str(a%10)
        a/=10
    return r[::-1]

The Explanation:

We need to understand the arithmetic behind this. For every 0 digit we see, we replace it with an ‘A’, which is 10. So, we decrease 10 from our number, because it is not zero anymore, but a ten. Then, we continue doing this just as if we are converting the number to another base. At the end, we have the reverse of the number, so, we return reverse.

The first if statement is actually unnecessary, it would work exactly the same without that if block.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s