題目概要:
10進位轉16進位,16進位轉10進位。
解題方向:
使用計概所教的方法去實作。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
class uva10473{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
while(sc.hasNext()){ | |
String s=sc.next(); | |
if(s.charAt(0)=='-') break; | |
if(s.charAt(0)=='0'){ | |
System.out.println(HTob10(s)); | |
}else{ | |
System.out.println(b10ToH(s)); | |
} | |
} | |
} | |
//16進位轉→10進位 | |
public static int HTob10(String st){ | |
int ans=0; | |
for(int i=st.length()-1;i>1;i--){ | |
int temp=st.charAt(i); | |
if(temp>=65) temp=temp-55; //temp-65+10 | |
else temp=temp-48; | |
ans=ans+(int)(temp*Math.pow(16,st.length()-i-1)); | |
} | |
return ans; | |
} | |
//10進位轉→16進位 | |
public static String b10ToH(String st){ | |
String ans=""; | |
int temp=Integer.parseInt(st); | |
while(temp>0){ | |
int c=temp%16; | |
if(c>=10) ans=(char)(65+c%10)+ans; | |
else ans=c+ans; | |
temp=temp/16; | |
} | |
ans="0x"+ans; | |
return ans; | |
} | |
} |
文章標籤
全站熱搜