- 题目:
- 题目描述
写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 ) - 输入描述
输入一个十六进制的数值字符串。 - 输出描述
输出该数值的十进制字符串。
- 题目描述
思路:对每个字符转成int然后求和
代码:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String value = scan.nextLine();
if(value == null){
return;
}
System.out.println(helper(value.substring(2,value.length())));
}
}
private static int helper(String str){
int len = str.length();
int count = 0;
int temp = 0;
int sum = 0;
for(int i = len - 1; i >= 0; i--){
char ch = str.charAt(i);
if(ch >= '0' && ch <= '9'){
temp = ch - '0';
}else if(ch >= 'a' && ch <= 'z'){
temp = ch - 'a' + 10;
}else if(ch >= 'A' && ch <= 'Z'){
temp = ch - 'A' + 10;
}
sum = sum + temp*(int)Math.pow(16,count);
count++;
}
return sum;
}
}
虽然上面的代码被AC了,但是仔细想想这种做法很可能导致溢出(类似大数相加算法)