問題描述
十六進制數是在程序設計時經常要使用到的一種整數的表示方式。它有0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F共16個符號,分別表示十進制數的0至15。十六進制的計數方法是滿16進1,所以十進制數16在十六進制中是10,而十進制的17在十六進制中是11,以此類推,十進制的30在十六進制中是1E。
給出一個非負整數,將它表示成十六進制的形式。
輸入格式
輸入包含一個非負整數a,表示要轉換的數。0<=a<=2147483647
輸出格式
輸出這個整數的16進製表示
樣例輸入
30
樣例輸出
1E
分析:按16取餘
代碼:
public static void main(String[] args) throws IOException {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
printToHexString(buf.readLine());
}
public static void printToHexString(String s) {
StringBuffer st = new StringBuffer();
int n = Integer.valueOf(s);
if(n == 0) {
System.out.println(0);
return;
}
int m;
while(n > 0) {
m = n % 16;
n = n / 16;//讓n一直除16,直到n小於0爲止,n被除了幾次,則轉換成的16進制就有幾位
switch(m) {
case 0:
st.insert(0, "0");//將字符串按順序插入到指定偏移量的st序列中
break;
case 1:
st.insert(0, "1");
break;
case 2:
st.insert(0, "2");
break;
case 3:
st.insert(0, "3");
break;
case 4:
st.insert(0, "4");
break;
case 5:
st.insert(0, "5");
break;
case 6:
st.insert(0, "6");
break;
case 7:
st.insert(0, "7");
break;
case 8:
st.insert(0, "8");
break;
case 9:
st.insert(0, "9");
break;
case 10:
st.insert(0, "A");
break;
case 11:
st.insert(0, "B");
break;
case 12:
st.insert(0, "C");
break;
case 13:
st.insert(0, "D");
break;
case 14:
st.insert(0, "E");
break;
case 15:
st.insert(0, "F");
break;
}
}
System.out.println(st);
}
}