思路:
- 16进制前必有0x或0X作为标志。
- 16进制转10进制时,末尾第一位乘16,第二位乘16此方,以此类推。
- 设定输入为字符串,依次将末尾的字符(0-9,A-F)提取,并与16的某次方相乘后相加。
- 最后识别出下一个字符为x或X即结束。
代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
int count = 1, result = 0, lastInt;
Scanner sc = new Scanner(System.in);
String string = new String();
string="";
while (sc.hasNext())
{
string = sc.next();
if(string.substring(0,2).equals("0x")||string.substring(0,2).equals("0X")) {
while (!string.equals("0x") || !string.equals("0X")) {
char lastChar = string.charAt(string.length() - 1);//取得最后一个字母
if (lastChar == 'x' || lastChar == 'X') {
//输出结果
System.out.println(result);
break;
}
switch (lastChar) {
case 'A':
case 'a':
lastInt = 10;
break;
case 'B':
case 'b':
lastInt = 11;
break;
case 'C':
case 'c':
lastInt = 12;
break;
case 'D':
case 'd':
lastInt = 13;
break;
case 'E':
case 'e':
lastInt = 14;
break;
case 'F':
case 'f':
lastInt = 15;
break;
default:
lastInt = Integer.parseInt(String.valueOf(lastChar));
break;
}
result += lastInt * count;
count *= 16;
string = string.substring(0, string.length() - 1);
}
}
string="";
count=1;
result=0;
}
}
}