5

我目前做了很多从 int 到 base36 字符串的转换(程序时间的 70%~)。这段代码有什么明显的优化吗?

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();
}
4

1 回答 1

17

您可以使用:

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

更容易维护,并且可能得到了很好的优化。

于 2012-04-04T10:00:26.533 回答