Chirag Parmar - 6 months ago 73

Java Question

I need to implement alphanumeric increment algorithm like

AAA001 should become AAA002

AAA999 should become AAB000 and so on.

All alphabets are in uppercase and letters are from 0-9.

There are some rules though, like some 000 or 666 should not come in a series. That can be done later on but I am in need of basic logic to implement the algorithm.

I would appreciate the help..

Answer

**For the solution which is not a true base 36:**

First, checks if the number ends with 9s. If so, increment the left part (A's). I'm not 100% sure it covers the corners cases though:

```
String number = "AAA999";
if (number.matches("[A-Z]*[9]*")) {
number = increment(number, 46656); //1000 base 36 in base 10
number = increment(number, -11997); //999 base 36 in base 10
} else {
number = increment(number, 1);
}
System.out.println(number);
private String increment(String number, int incr) {
int integerValue = Integer.parseInt(number, 36) + incr;
return Integer.toString(integerValue, 36).toUpperCase();
}
```

Or this, with less conversion between String and int:

```
String number = "AAA999";
int integerValue = Integer.parseInt(number, 36);
if (number.matches("[A-Z]*[9]*")) {
integerValue = integerValue + 46656; //1000 base 36 in base 10
integerValue = integerValue - 11997; //999 base 36 in base 10
} else {
integerValue++;
}
number = Integer.toString(integerValue, 36);
System.out.println(number);
```