Lanqiao Cup Test Questions-Basic Practice Decimal to Hexadecimal

Resource limit
Time limit: 1.0s
Memory limit: 512.0MB

Problem description
Hexadecimal number is a representation of integer that is often used in program design. It has 16 symbols of 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F, representing the decimal number 0 to 15. Hexadecimal counting method is full hexadecimal 1, so decimal number 16 is 10 in hexadecimal, and decimal 17 is 11 in hexadecimal, and so on, decimal 30 is in hexadecimal The system is 1E.
Give a non-negative integer and express it in hexadecimal form.

Input format   
input comprises a non-negative integer a, represents a number to be converted. 0 <= a <= 2147483647
output format   
outputs the hexadecimal integer input sample 30 sample output 1E

import java.util.*;
 
public class Main {
    
    
	
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		long a  = sc.nextLong();
		StringBuilder str = new StringBuilder();
		int x;
		if(a==0){
    
    
			System.out.println(0);
			return ;
		}
		while(a>0){
    
    
			x = (int) (a % 16);
			switch(x){
    
    
			case 10: str.append("A");break;
			case 11: str.append("B");break;
			case 12: str.append("C");break;
			case 13: str.append("D");break;
			case 14: str.append("E");break;
			case 15: str.append("F");break;
			default: str.append(String.valueOf(x));break;
			}
			a = a/16;
		}
		StringBuilder ans = new StringBuilder();
		for(int i=str.length()-1;i>=0;i--){
    
    
			ans.append(str.charAt(i)); 
		}
		System.out.println(ans);
	}
}

Guess you like

Origin blog.csdn.net/TroyeSivanlp/article/details/108685492