本文发表在 rolia.net 枫下论坛public class Z0ToString {
public static void main(String[] args) {
for (int i = 0; i < 10000000; i++) {
String convertedValue = convertBaseTenToString(i);
System.out.println("i=" + i + " " + convertedValue);
if (i!= convertStringToBaseTen(convertedValue)) {
throw new RuntimeException("not equal: i = " + i + " convertStringToBaseTen(a)="+ convertStringToBaseTen(convertedValue));
}
}
}
static String convertBaseTenToString(int number) {
char[] digits = { 'A', '0', 'A', '0', 'A', '0' };
for (int i =digits.length -1; i>=0;i-- ) {
int divisor = (i%2 !=0) ? 10 : 26;
int a = (int)digits[i];
int b = (a+ number % divisor);
digits[i] = (char)b ;
number /= divisor;
}
return new String(digits);
}
static int convertStringToBaseTen(String number) {
int returnNumber=0;
int base =1 ;
for (int i = number.length()-1; i>=0; i--) {
if (i%2 ==0) {
int value = (number.charAt(i) -((int)'A'));
if (i!= number.length()-1 ) {
base = base * 10;
}
returnNumber = value* base + returnNumber;
} else {
int value = (number.charAt(i) -(int)'0');
if (i!= number.length()-1 ) {
base = base * 26;
}
returnNumber = value* base + returnNumber;
}
}
return returnNumber;
}
}更多精彩文章及讨论,请光临枫下论坛 rolia.net
public static void main(String[] args) {
for (int i = 0; i < 10000000; i++) {
String convertedValue = convertBaseTenToString(i);
System.out.println("i=" + i + " " + convertedValue);
if (i!= convertStringToBaseTen(convertedValue)) {
throw new RuntimeException("not equal: i = " + i + " convertStringToBaseTen(a)="+ convertStringToBaseTen(convertedValue));
}
}
}
static String convertBaseTenToString(int number) {
char[] digits = { 'A', '0', 'A', '0', 'A', '0' };
for (int i =digits.length -1; i>=0;i-- ) {
int divisor = (i%2 !=0) ? 10 : 26;
int a = (int)digits[i];
int b = (a+ number % divisor);
digits[i] = (char)b ;
number /= divisor;
}
return new String(digits);
}
static int convertStringToBaseTen(String number) {
int returnNumber=0;
int base =1 ;
for (int i = number.length()-1; i>=0; i--) {
if (i%2 ==0) {
int value = (number.charAt(i) -((int)'A'));
if (i!= number.length()-1 ) {
base = base * 10;
}
returnNumber = value* base + returnNumber;
} else {
int value = (number.charAt(i) -(int)'0');
if (i!= number.length()-1 ) {
base = base * 26;
}
returnNumber = value* base + returnNumber;
}
}
return returnNumber;
}
}更多精彩文章及讨论,请光临枫下论坛 rolia.net