/* * Test case * With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-": * Write out a, b and c in decimal notation; * Calculate a × (b − c), write out the result in both ternary and decimal notations. */ public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); //result=a*(b-c) BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;ib.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }