题解 | #进制转换#
进制转换
http://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
1.十六进制转十进制公式: 要从右到左用二进制的每个数去乘以16的相应次方,然后这些数字相加就可以了
2.利用count对应位数
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String num = sc.nextLine(); int length = num.length(); int count = 0; int sum = 0; for(int i = length-1; i>=2; i--){ if(num.charAt(i)=='A'){ sum += Math.pow(16,count)*10; }else if(num.charAt(i)=='B'){ sum += Math.pow(16,count)*11; }else if(num.charAt(i)=='C'){ sum += Math.pow(16,count)*12; }else if(num.charAt(i)=='D'){ sum += Math.pow(16,count)*13; }else if(num.charAt(i)=='E'){ sum += Math.pow(16,count)*14; }else if(num.charAt(i)=='F'){ sum += Math.pow(16,count)*15; }else { sum += Math.pow(16,count)*Integer.parseInt(num.substring(i,i+1)); } count++; } System.out.println(sum); } } }