If have any suggestion please recommend. Here is my solution as codegym is not allowing to attach my solution
public void createExpression(int number) {
String num = convertToTerinanry(number);
String perNum = convertToPrefectTerninary(num);
String result = String.valueOf(number)+" = ";
int cal = 0;
for(int i = perNum.length()-1,power = 0 ; i >= 0 ; i--,power++){
if(perNum.charAt(i) == '1'){
cal = (int) Math.pow(3,power);
result += "+ "+cal+" ";
}
if(perNum.charAt(i) == 'z'){
cal = (int)Math.pow(3,power);
result += "- "+cal+" ";
}
}
System.out.println(result);
}
private String convertToTerinanry(int x){
int a = x % 3;
int b = x / 3;
String result = String.valueOf(a);
if(b > 0){
return convertToTerinanry(b)+result;
}
return result;
}
private String convertToPrefectTerninary(String number){
String result = "";
int[] carr = new int[8];
for(int i = 0 ; i < carr.length ; i++)
carr[i] = 0;
for(int i = (carr.length - number.length()),counter = 0 ; i < carr.length ; i++,counter++){
carr[i] = Character.getNumericValue(number.charAt(counter));
}
for(int i = carr.length-1 ; i >= 0 ; i--){
if(carr[i] == 1)
continue;
if(carr[i] == 2 && i != 0){
carr[i] = -1;
carr[i-1] += 1;
}
if(carr[i] == 3 && i != 0){
carr[i] = 0;
carr[i-1] += 1;
}
}
for(int i = 0 ; i < carr.length ; i++){
if(carr[i] == -1){
result += "z";
continue;
}
result += carr[i];
}
return result;
}
I have solved it but wants to improve my solution .
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
June Sung Park
2 September 2020, 05:25
I applied the code available at https://www.geeksforgeeks.org/balanced-ternary-number-system/ that converts an integer into a balanced ternary number (which has about 10 lines). This, for example, generates a ternary number 10Z1Z for 74. Then I just needed to convert the ternary number (say, output string in the code below) into the expression "74 = - 1 + 3 - 9 + 81". This part goes through the output string character by character as follows:
for (int i = output.length()-1; i >= 0; i--) {
char ch = output.charAt(i);
if (ch == 'Z') System.out.print(" - " + (int)Math.pow(3, output.length()-i-1));
else if (ch == '1') System.out.print(" + " + (int)Math.pow(3, output.length()-i-1)); }
That's it. Hope this helps.
+4
Guadalupe Gagnon
28 January 2020, 20:43
I messaged you
0