# Base Convert

![](https://248377266-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LI6ewAwekr0-u25tzzj%2F-LYT9RsAFnYybC3E8waN%2F-LYT9kuPLjwcFkxONFSV%2Fimage.png?alt=media\&token=f373a9aa-8dfe-4d04-8ec9-94d48359782a)

10-15 <=> 'A' - 'F'转换

&#x20;

```
10-15转到字母
'A' + [digit] - 10;
字母'A'-'F'到数字 10=15
char-'A'+10

```

```java
public static String convertBase(String numAsString, int b1, int b2) {
    // TODO - you fill in here.

    int decimal = 0;
    boolean isNeg = false;
    if (numAsString.charAt(0) == '-') isNeg = true;

    for (int i = isNeg ? 1:0; i < numAsString.length(); i++){
//      decimal = decimal*b1 + toDecimal(numAsString.charAt(i));

      decimal = decimal*b1 + (Character.isDigit(numAsString.charAt(i))?
              numAsString.charAt(i) - '0' : numAsString.charAt(i) - 'A' +10);
    }

    decimal = isNeg ? - decimal: decimal;
    StringBuilder sb = new StringBuilder();
    do {
      int tmp = Math.abs(decimal % b2);
      sb.append((char)(tmp < 10 ? '0'+tmp : 'A' + tmp - 10));
      decimal /= b2;
    }while (decimal != 0);

    if (isNeg) sb.append('-');
    sb.reverse();

    return sb.toString();
  }
```

时间复杂度：

![](https://248377266-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LI6ewAwekr0-u25tzzj%2F-LYTDw294rFYR9_wzUp2%2F-LYTEdBblmpJr83Ah5KO%2Fimage.png?alt=media\&token=6099f72d-9c37-48d7-b0b7-eb6797f27570)
