1、17进制转10进制
代码如下:
/**
* @param str:待转换的字符串
* @return int :转换后的结果
*/
public static int con(String str) {
int t = 0, sum = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) <= '9') {
t = str.charAt(i) - '0';
} else {
t = str.charAt(i) - 'A' + 10;
}
//方法一
//sum = sum * 17 + t; //主要利用二进制的短除法的思想
//方法二
//sum = (int) (sum + t * java.lang.Math.pow(17, str.length() - i - 1)); //利用pow公式
}
return sum;
}
经过测试,当输入的字符串越长时,方法二(pow运算)非常耗时
下面是我现场做的,分享一下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 17进制转10进制
*
* @author andy 2013-06-14
*
*/
public class ConvertToTen {
public static char[] arr = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
/** N表示进制 */
public static int N = 17;
/**
* 获取输入字符
*
* @return
* @throws IOException
*/
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s.toUpperCase();
}
/**
* 进制转换
*
* @param input:17进制字符串
* @return int:10进制结果
*/
public static int convertToTen(String input) {
int i = 0;
int strLen = input.length();
int result = 0;
for (i = 0; i < strLen; i++) {
int tempResult = 1;
int j = i;
while (j < strLen - 1) {
tempResult *= N;
j++;
}
char c = input.charAt(i);
tempResult *= getIndex(c);
result += tempResult;
}
return result;
}
/**
* 返回c字符的数组下标
*
* @param c
* @return int:字符c在数组中的下标
*/
public static int getIndex(char c) {
for (int i = 0, j = arr.length; i < j; i++) {
if (c == arr[i]) {
return i;
}
}
return -1;
}
/**
* 判断输入字符是否合法
*
* @param input:输入字符
* @return boolean:<code>ture</code>合法;<code>false</code>不合法
*/
public static boolean isIn(String input) {
return input.matches("^[0-9A-G]+$");
}
/**
* 主函数
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
try {
while (true) {
String input = getString();
if (input.equals("") || !isIn(input)) {
System.out.println("Invalid input,Enter again:");
continue;
}
System.out.println( convertToTen(input));
}
} catch (Exception e) {
e.printStackTrace();
}
}
2、字符串压缩
代码如下:
public static String zip(String str) {
StringBuffer sb = new StringBuffer();
int count = 1;
for (int i = 0, len = str.length(); i < len - 1; i++) {
if (str.charAt(i) == str.charAt(i + 1)) {
count++;
if (len - 2 == i) {
sb.append("" + count + str.charAt(i));
}
} else {
sb.append("" + (count > 1 ? count : "") + str.charAt(i));
if(len-2==i){
sb.append(str.charAt(i+1));
}
count = 1;
}
}
return sb.toString();
}