2

How can I convert a number to its equivalent in base9 with the caveat that its base9 has no "0" digit.

For example:
Base10 = 0, 1, 2, 3, .. 9, 10, 12 ... 28, 29, 30, ... 62, 63, 64, etc
Base9 = N/A, 1, 2, 3, .. 9, 11, 12 ... 31, 32, 33, ... 68, 69, 71, etc

I want to be able to take a normal decimal number (ex:10) and have it returned in base9 ignoring the 0 place (ex:11).

I'm new to python and programming in general, not to mention my lack of knowledgeable as far as math is concerned, so my first attempt is rather sloppy. It only works on smaller numbers and I have a feeling there's a much easier way to do this.

def base9(x):
    count = 0
    a = xrange(10,100,9)
    while count != x:
        if x < a[count]:
            return x + count
        count += 1


print base9(10)

4 Answers4

2

Convert the number to normal base 9. Then add 1 to the lowest-order digit, as well as all other digits except the highest-order digit (this means that when the number is 1 digit long, we add 1 to it).

E.g.

  • 12 -> 13 (normal base 9) -> 14 (modified base 9)
  • 9 -> 10 (normal base 9) -> 11 (modified base 9)
  • 100 -> 121 (normal base 9) -> 132 (modified base 9)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I think Base10 is 0,1,2,3,4,5,6,7,8,9, and Base9 is 0,1,2,3,4,5,6,7,8.

The digits "10" is 1*10 + 0*1 in base 10, and 1*9 + 0*1 in base 9.

Bor
  • 189
  • 7
  • I think that too, but too don't think this answers the question. – doctorlove Sep 02 '13 at 11:57
  • Actually I am not quite clear about the question. I don't know what the questioner really wanted to do. – Bor Sep 02 '13 at 12:11
  • I updated the OP a bit to try and make it more clear what I'm asking for. I want a function that translates a number into base 9, with it's base9 have the digits 1-9 instead of 0-8. – user2739591 Sep 02 '13 at 12:25
0

Base 9 can have a zero, for example 0 is 0. 10 is 1*9 + 0*1 = 9. However, it cannot have a 9. Each digit tells you how many lots of the ascending powers of nine to sum together.
You should probably check if you get a negative number on the way in.
For each input, keep dividing by 9 and checking the remainder.

def base9(x):
    sign = 1
    if x < 0:
    sign = -1
    x *= -1
    result = 0
    index = 0
    while x > 0:
        result += (x%9) * 10**index
        x /= 9
        index += 1
    return result*sign
doctorlove
  • 18,872
  • 2
  • 46
  • 62
0

base9 is integers made up with 0, 1, 2, 3, ..., 8, without 9. For example, a 4 digits base9 int abcd = a*9^3 + b*9^2 + c*9^1 + d*9^0, and a, b, c, d is from {0, 1, 2, 3, 4, 5, 6, 7, 8}. So, 11(base9) = 1*9^1 + 1*9^0 = 10(base10). Here's my code for converting the positive base10 int into base9:

def base9(x):
    digits = []
    base9_int = 0
    while x > 0:
        digits.append(x % 9)
        x = int(x / 9)
    for x in digits[::-1]:
        base9_int = base9_int * 10 + x
    return base9_int

for each in range(1, 91):
    print base9(each) 
KMHook
  • 85
  • 1
  • 1
  • 7