将长度为3的Base 62字符串反转为整数

时间:2018-03-21 10:09:06

标签: java algorithm

我已经获得了以下代码来将Integer转换为长度为3的Base62字符。有没有办法可以将其反转以获取初始Integer?

示例:以下代码将整数238328转换为" zzz"这就是我想要的。有没有办法可以使用" zzz"并回到整数238328?

private static final String CHARACTERS = "0123456789"
        + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        + "abcdefghijklmnopqrstuvwxyz";
private static final int MAX_NUMBER = 238328;
private static final int BASE = CHARACTERS.length();

static String generateCode(int num) {
    if (num < 1 || num > MAX_NUMBER) {
        throw new IllegalArgumentException("Illegal input value: " + num);
    }

    int value = num - 1;

    char firstChar = CHARACTERS.charAt(((value / BASE) / BASE) % BASE);
    char secondChar = CHARACTERS.charAt((value / BASE) % BASE);
    char thirdChar = CHARACTERS.charAt(value % BASE);
    return new String(new char[]{firstChar, secondChar, thirdChar});
}

转换整数7815给了我&#34; 222&#34;。

试图通过以下代码无法解决上述问题。

static int generateNumber(){
    //hardcoding "222" to test it out
    int firstChar = 2 * BASE * BASE / BASE; 
    int secondChar = 2 * BASE / BASE;
    int thirdChar = 2 % BASE;

    return firstChar + secondChar + thirdChar;
}

我想保持生成的String总是长度为3,因此与简单地将数字从一个基数转换为另一个基数类似。

1 个答案:

答案 0 :(得分:1)

您正在寻找:

private static int generateNumber(String str){
  if(str.length() == 3) {

    char fisrtChar = str.charAt(0);
    char secondChar = str.charAt(1);
    char thirdChar = str.charAt(2);

    int firstInt = CHARACTERS.indexOf(fisrtChar) * BASE * BASE; 
    int secondInt = CHARACTERS.indexOf(secondChar) * BASE;
    int thirdInt = CHARACTERS.indexOf(thirdChar);

    return firstInt + secondInt + thirdInt + 1;
  }
  return 0;
}