SunnyX
asked on
Core Java. Improving algorithm ( get rid of switch-case statement )
I need to map real number to another numer system ( from 2 to 16 ).
Like this one http://planetcalc.com/862/
I come up with solution below. However, I need to make further improvement of the algorithm. Particularly speaking, I need to get rid of switch-case statement when I map letters. I feel that the solution will be through ASCII table ( http://www.ascii-code.com/ ) . Please tell how to elegant version of the solution will be look like ( I probably should work thought StringBuilder if so what method best to use ) . Thx in advance !
Like this one http://planetcalc.com/862/
I come up with solution below. However, I need to make further improvement of the algorithm. Particularly speaking, I need to get rid of switch-case statement when I map letters. I feel that the solution will be through ASCII table ( http://www.ascii-code.com/ ) . Please tell how to elegant version of the solution will be look like ( I probably should work thought StringBuilder if so what method best to use ) . Thx in advance !
public class Task {
public static void main(String[] args) {
int number = 1289;
int N = 2; // radix = 2...16
if (N < 2 && N > 16) {
System.out.println("Radix is out of bounds");
return;
}
if (number < 0) {
System.out.println("Number is not natural");
return;
}
if (number == 0) {
System.out.println("0");
return;
}
System.out.println(trans(number, N));
}
public static String trans(int num, int N) {
if (num == 0) {
return "";
}
String str;
switch (num % N) {
case 10:
str = "A";
break;
case 11:
str = "B";
break;
case 12:
str = "C";
break;
case 13:
str = "D";
break;
case 14:
str = "E";
break;
case 15:
str = "F";
break;
default:
str = String.valueOf(num % N);
}
return trans(num/N, N) + str;
}
}
ASKER
thx for attention. I need that realization was recursive light weight function. Anyway, I would like to stick with my realization and just improve it a little bit
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thx so much ! a lot of respects !
I thought you may have had another use for the switch ?
Btw, your translator is a nice piece of code. I wish I'd written it. l)
Btw, your translator is a nice piece of code. I wish I'd written it. l)
ASKER
I thought you may have had another use for the switch ?
Btw, your translator is a nice piece of code. I wish I'd written it. l)
Thx for your complement ! much appreciation. Please follow me I promise there will be a lot of nice piece of code to improve :)
I follow you already :)
Ok
Open in new window