How to convert from unbalanced to balanced ternary?

Note that 2 in ternary is +- in balanced ternary, or in decimal 2 = 3 - 1. So if you start with an array filled with 0s, 1s, and 2s, just replace every 2 with a -1 and add 1 to the number to its left. (Make sure you have an extra 0 at the beginning of the number, at least if it starts with a 2.) Depending on how you do the replacement you may also need to replace 3s with 0s, adding 1 to the left as usual. Then repeat the process until there are no more 2s (or 3s).


One way of seeing it is, if you are getting a remainder 2 with a remaining quotient of x, it is equivalent to getting a remainder of -1 with a remaining quotient of x+1.

Converting it then is like simple conversion to a ternary base, with one extra check.

String output="";
while (n>0) {
   rem = n%3;
   n = n/3;
   if (rem == 2) {
       rem = -1;
       n++;
   }
   output = (rem==0?'0':(rem==1)?'+':'-') + output;
}

The running program can be found here.