Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing converting int to base36

I currently do a lot of conversions from int into a base36 string (70%~ of programs time). Are there any obvious optimisations to this code?

public static final String alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
public static StringBuilder b = new StringBuilder();
public static String sign = "";

public static String convertToBase36(int number)
{
    if (number == 0)
    {
        return "0";
    }

    b.delete(0, b.length());

    sign = "";
    if (number < 0)
    {
        sign = "-";
        number = -number;
    }

    int i = 0;
    int counter = 10;

    while (number != 0 && counter > 0)
    {
        counter--;
        i = number % 36;
        number = (number - i)/36;
        b.append(alphabet.charAt(i));

    }           

    return sign + b.reverse().toString();
}
like image 698
Jamie Avatar asked Apr 04 '12 09:04

Jamie


1 Answers

You can use:

String s = Integer.toString(100, 36);
int i = Integer.parseInt("2s", 36);

Easier to maintain, and probably well optimized.

like image 61
Vivien Barousse Avatar answered Oct 14 '22 18:10

Vivien Barousse