日期:2014-05-20  浏览次数:20570 次

求助,蓝桥杯中十六进制转换为十 提示错误、、、
import java.util.Scanner;

/*
 * 十进制转十六进制
 * 
 * */

public class Main_16To10 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in) ;
String str = scan.next() ;
StringBuffer sb = new StringBuffer(str) ;
str = sb.reverse().toString() ;
if(str.length()<=8)
{
int sum = 0 ;
char ch[] = str.toCharArray() ;

for(int i=ch.length-1;i>=0;i--)
{
if(Character.isDigit(ch[i]))
{
sum += ch[i]*Math.pow(16, i) ;
}
else
{
sum +=to10(ch[i])* Math.pow(16, i) ;
}
}
System.out.println(sum);
}
}

public static int to10(char ch)
{
int iResult = 0 ;
switch(ch)
{
case  'A' :
iResult = 10 ;
break ;
case 'B' :
iResult = 11 ;
break ;
case 'C' :
iResult = 12 ;
break  ;
case 'D' :
iResult = 13 ;
break ;
case 'E' :
iResult = 14 ;
break ;
case 'F' :
iResult = 15 ;
break ;
}
return iResult ;
}

}

------解决方案--------------------
这里:
sum += ch[i]*Math.pow(16, i) ;
直接用ch[i]去计算,就不对了。应该用
Integer.parseInt("" + ch[i])