# Convert to and from signed octal [closed]

Write some code to do the following:

1. Take as its input a signed integer in either signed decimal or signed octal (explained below)
2. If the number is decimal convert it to octal. If it's octal, convert it to decimal
3. Output the number!

Instead of starting with a 0, negative octal numbers will start with a Z (capital zed). In the same way that -1 is commonly encoded in binary as all 1s, in signed octal it is encoded as all 7s. -2 is all 7s except for the final digit which is 6, and so on.

Your code must accept leading 0s, or 7s (after the initial Z in octal) but must not output leading 0s for decimal or non-negative octal, with the exception of a single 0 to indicate octal format, and must not output leading 7s in the case of negative octal. 0 is valid as an entire number in both decimal and octal and is the only number to have an identical representation in both. Decimal numbers must not have any leading zeros and must be interpreted as octal if they do (i.e. 08 should be interpreted as neither decimal nor octal). Note that 0s immediately after the Z are significant and must not be truncated. Z is shorthand for an infinite number of 7s. You may assume that the input will always be valid and not check for it in your code.

 Input : Output
-1 : Z
-10: Z66
-5: Z3
10: 012
-30000: Z05320
-10000: Z54360
0  : 0
01234: 668
Z1234: -3428
Z77777: -1
00777: 511
Z6000: -1024


A table of the first few positive and negative signed octal numbers:

+ve -ve
0   0
01  Z
02  Z6
03  Z5
04  Z4
05  Z3
06  Z2
07  Z1
010  Z0
011 Z67
012 Z66


Make it small!

• Doesn't octal zero have to be 00? Commented Jul 3, 2016 at 13:07
• Could you remove the second part of the challenge (overflow) as it is not very related? Commented Jul 3, 2016 at 13:16
• 1. "Decimal numbers must not have any leading digits and must be interpreted as octal if they do." What does this mean? It seems to contradict itself. 2. How many bits are required to represent a negative number? 3. It took me some careful thinking to realise that Z is shorthand for an infinite string of ..777. But then the natural representation for -1 seems to be Z rather than Z7. Can answers give either in output? Can they choose to accept only one in input? Commented Jul 3, 2016 at 20:57
• @PeterTaylor - Replace "digits" with "zeroes", I think. Commented Jul 6, 2016 at 13:22
• @PeterTaylor I did mean "digits" but I've changed it to "0"s and "7"s. Commented Jul 7, 2016 at 22:15