藍橋杯 基礎練習 十六進制轉十進制 java

package jinzhizhuanhuan;
import java.util.Scanner;
public class HextoDecimal {
	public static int compare(char ch){//將A~F轉換爲對應的十進制數
		int[]a=new int[75];
		int k=65,i=10;//A的assic碼爲65
		while(i<16)a[k++]=i++;//a['A']=10,依次類推
		return a[ch];
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		while(sc.hasNext()){
			//StringBuider hex=new StringBuilder();
			String str=sc.nextLine();
			//StringBuilder sb=new StringBuilder(str);
			String hex=new StringBuilder(str).reverse().toString();
			//System.out.println(hex);
			int t=0;
			long result=0;
			while(t<hex.length()){
				if('A'<=hex.charAt(t)&&hex.charAt(t)<='F'){
					int b=compare(hex.charAt(t));
					//System.out.println(b);
					result+=b*(long)Math.pow(16,t++);
				}
				else{
					int tem=hex.charAt(t)-'0';
					result+=tem*(long)Math.pow(16,t++);
				}
			}
			System.out.println(result);
		}
	}
}

當然還有一個更簡單的辦法,就是使用java類來實現

import java.util.Scanner;
public class Main{
	public static void main(String[]args){
		Scanner sc=new Scanner(System.in);
		while(sc.hasNext()){
			String hex=sc.nextLine();
			System.out.println(Long.parseLong(hex,16));
		}
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章