import java.util.HashMap;
import java.util.Map;
public class Number {
public static Character[] format = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
public static Map<Character, Integer> formatMap = new HashMap<Character, Integer>(format.length);
static {
for (int i = 0; i < format.length; i++) {
formatMap.put(format[i], i);
}
}
public static void main(String[] args) {
try {
String transfor = transfor("11k01.", 2, 10);
System.out.println("转换后的值为:" + transfor);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
public static String transfor(String value, int source, int destination) throws IllegalArgumentException {
if (value == null || value.trim().length() == 0 || source < 2 || source > 36 || destination < 2 || destination > 36) {
throw new IllegalArgumentException(String.format("参数有误,请检查参数是否正确(value不能为空,2 <= source <= 36,2 <= destination <= 36).\n您的输入为:\nvalue = \"%s\"\nsource = %d\ndestination = %d", value, source, destination));
}
value = value.trim();
if (source == destination) {
return value;
}
int num = 0;
if (source == 10) {
num = Integer.parseInt(value);
} else {
int length = value.length();
for (int index = 0; index < length; index++) {
Integer charValue = formatMap.get(value.charAt(length - 1 - index));
if (charValue != null && charValue < source) {
num += charValue * Math.pow(source, index);
} else {
throw new IllegalArgumentException(String.format("入参\"%s\"不是%d进制数", value, source));
}
}
}
System.out.println("十进制数为:" + num);
if (destination == 10) {
return String.valueOf(num);
}
StringBuilder sb = new StringBuilder();
while (num > 0) {
int modResult = num % destination;
num = num / destination;
sb.append(format[modResult]);
}
StringBuilder result = new StringBuilder();
int sbLength = sb.length();
for (int index = 0; index < sbLength; index++) {
result.append(sb.charAt(sbLength - 1 - index));
}
return result.toString();
}
public static String transforGo(String value, int source, int destination) throws IllegalArgumentException {
if (value == null || value.trim().length() == 0 || source < 2 || source > 36 || destination < 2 || destination > 36) {
throw new IllegalArgumentException(String.format("参数有误,请检查参数是否正确(value不能为空,2 <= source <= 36,2 <= destination <= 36).\n您的输入为:\nvalue = \"%s\"\nsource = %d\ndestination = %d", value, source, destination));
}
value = value.trim();
if (source == destination) {
return value;
}
int num = 0;
return null;
}
}