10進制轉16進制

問題描寫敘述
  十六進制數是在程序設計時經常要使用到的一種整數的表示方式。

 

它有0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F共16個符號,分別表示十進制數的0至15。java

十六進制的計數方法是滿16進1,因此十進制數16在十六進制中是10,而十進制的17在十六進制中是11,以此類推,十進制的30在十六進制中是1E。
  給出一個非負整數,將它表示成十六進制的形式。git

 

輸入格式
  輸入包括一個非負整數a,表示要轉換的數。0<=a<=2147483647
輸出格式
  輸出這個整數的16進製表示
例子輸入
30
例子輸出
1E
 
import java.io.*;
class Main
{
	public static void main(String[] args)throws Exception 
	{
		BufferedReader bf = new BufferedReader(
			new InputStreamReader(System.in));
		int a = Integer.parseInt(bf.readLine());
		String s = fun(a);
		System.out.println(s);
	}
	public static String fun(int i){
		String s = new String ("0123456789ABCDEF");
		char [] buf = new char[32];
		int charPos=32;
		int radix=1<<4;
		int mask = radix-1;
		do
		{
			buf[--charPos]=s.charAt(i&mask);
			i>>>=4;
		}
		while (i!=0);
		return new String(buf,charPos,(32-charPos));
	}
}
-----------
mport java.io.*;
class Main
{
	final static char[] digits = {
		'0' , '1' , '2' , '3' , '4' , '5' ,
		'6' , '7' , '8' , '9' , 'a' , 'b' ,
		'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
		'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
		'o' , 'p' , 'q' , 'r' , 's' , 't' ,
		'u' , 'v' , 'w' , 'x' , 'y' , 'z'
		};	
	public static void main(String[] args)throws Exception 
	{
		BufferedReader bf = new BufferedReader(
			new InputStreamReader(System.in));
		int a = Integer.parseInt(bf.readLine());
		String s = fun(a).toUpperCase();
		System.out.println(s);
	}
	public static String fun(int i){
		char [] buf = new char[32];
		int charPos=32;
		int radix=1<<4;
		int mask = radix-1;
		do
		{
			buf[--charPos]=digits[i & mask];
			i>>>=4;
		}
		while (i!=0);
		return new String(buf,charPos,(32-charPos));
	}
}
相關文章
相關標籤/搜索