蓝桥杯基础-014-Decimal_To_Hexadecimal

题意

输入一个整数n(0 <= n <= 2147483648)

(其中java中 int [ -2^31 , 2^31 ] <- 32 = 4*8)&& 2^31 = 2147483648)->即n 为 int 即可

代码

import java.util.Scanner;


public class Main {

	public static void main(String[] args) {

		char[] HexDecimalAlphabet = new char[16];
		char[] A_F_Alphabet = {'A','B','C','D','E','F'};
		char[] Stack = new char[8];
 		for (int i = 0; i < HexDecimalAlphabet.length; i++) {
			if(i<10)
				HexDecimalAlphabet[i] = (char)((int)'0'+i);
			else
				HexDecimalAlphabet[i] = A_F_Alphabet[ i%10 ];
 		}

 		Scanner keyin = new Scanner(System.in);
 		int n = keyin.nextInt();
 		int cnt = 0;
 		do{
 			Stack[cnt] = HexDecimalAlphabet[n % 16];
 			cnt++;
 			n = n / 16;
 		}while( n != 0);
 		for (int i = cnt - 1; i >= 0; i--) {
			System.out.print(Stack[i]);
		}
	}
}
Summary

i) 先建立HexadecimalAlphabet对映表; 

ii ) 对n进行取位数操作(1.n MOD 16, 2. n /= 16,3. while(n != 0) <-欧几里得算法) ; 

iii) ch = HexdicimalAlphabet[sub (= MOD所得数)] && 压栈(或记入数列) ; 

iv) 出栈(逆序输出数列)

你可能感兴趣的:(蓝桥基础题)