题目描述
写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 )
输入描述:
输入一个十六进制的数值字符串。
输出描述:
输出该数值的十进制字符串。
示例1
输入
0xA
输出
10
问题解决
思路:另写一个函数来处理进制转换。用substring()去掉十六进制的0x,再进行转换。对A-F特殊处理转化为对应的数字。对0-9直接将char转化为int数字。
import java.util.Scanner;
/**
* 写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 )
* @author Administrator
*
*/
public class Main {
* 写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 )
* @author Administrator
*
*/
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
change(str);
}
}
private static void change(String s){
s = s.toUpperCase();
s = s.substring(2, s.length());
char[] ch = s.toCharArray();
int num=0;
int len = ch.length-1;
for(int i=0; i<ch.length; i++){
int temp =0;
if(ch[i] == 'A'){
temp = 10;
}else if(ch[i] == 'B'){
temp = 11;
}else if(ch[i] == 'C'){
temp = 12;
}else if(ch[i] == 'D'){
temp = 13;
}else if(ch[i] == 'E'){
temp = 14;
}else if(ch[i] == 'F'){
temp = 15;
}else{
temp = ch[i] - '0'; //将char转化为int
}
double b = len -i;
num += temp*Math.pow(16, b);
}
System.out.println(num);
}
while(sc.hasNext()){
String str = sc.nextLine();
change(str);
}
}
private static void change(String s){
s = s.toUpperCase();
s = s.substring(2, s.length());
char[] ch = s.toCharArray();
int num=0;
int len = ch.length-1;
for(int i=0; i<ch.length; i++){
int temp =0;
if(ch[i] == 'A'){
temp = 10;
}else if(ch[i] == 'B'){
temp = 11;
}else if(ch[i] == 'C'){
temp = 12;
}else if(ch[i] == 'D'){
temp = 13;
}else if(ch[i] == 'E'){
temp = 14;
}else if(ch[i] == 'F'){
temp = 15;
}else{
temp = ch[i] - '0'; //将char转化为int
}
double b = len -i;
num += temp*Math.pow(16, b);
}
System.out.println(num);
}
}