题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
就注意两点:
1.去掉字符串里的‘0x’之后对乘幂的使用
2.注意char 0~9参与运算要把它转成int,强制转换会转成char对应的ascII码,而不是对应的数字值
用Character.getNumericValue();函数来进行转换。
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String shiliu = in.next();
int len = shiliu.length();
//System.out.println("len: "+len);
char[] arr = shiliu.toCharArray();
int res = 0;//shi jin zhi shu
int temp = 0;
for(int i=2;i<len;i++){
switch(arr[i]){
case 'A':
res += 10*Math.pow(16,(len-i-1));
break;
case 'B':
res += 11*Math.pow(16,(len-i-1));
break;
case 'C':
res += 12*Math.pow(16,(len-i-1));
break;
case 'D':
res += 13*Math.pow(16,(len-i-1));
break;
case 'E':
res += 14*Math.pow(16,(len-i-1));
break;
case 'F':
res += 15*Math.pow(16,(len-i-1));
break;
default:
temp = Character.getNumericValue(arr[i]);
res += temp*Math.pow(16,(len-i-1));
}
//System.out.println(arr[i]);
//System.out.println("(int)arr[i] "+(int)arr[i]);
//这样强制转换是char '2' 转成int 输出的是他的ascII码67
//System.out.println("第"+(i-1)+"次"+res);
}
System.out.print(res);
}
}
查看5道真题和解析