Discuss / Java / 练习:10进制转16进制

练习:10进制转16进制

Topic source

D

#1 Created at ... [Delete] [Delete and Lock User]


import java.util.*;



public class Main {

    public static void main(String[] args) {

        String hex = toHex(12500);

        if (hex.equalsIgnoreCase("30D4")) {

            System.out.println("测试通过");

        } else {

            System.out.println("测试失败");

        }

    }



    static String toHex(int n) {

    	Deque<String> stack = new LinkedList<>();

    	StringBuilder sb = new StringBuilder();

    	int remainder, quotient;

    	do {

    		quotient = n / 16;

			remainder = n % 16;

			n = quotient;

			

			if (remainder < 10)

				stack.push(String.valueOf(remainder));

			else {

				switch (remainder) {

				case 10:

					stack.push("A");

					break;

				case 11:

					stack.push("B");

					break;

				case 12:

					stack.push("C");

					break;

				case 13:

					stack.push("D");

					break;

				case 14:

					stack.push("E");

					break;

				case 15:

					stack.push("F");

					break;

				default:

					break;

				}

			}

		} while (quotient != 0);

    	

    	while (!stack.isEmpty()) {

    		sb.append(stack.pop());

    	}

    	

        return sb.toString();

    }

}




  • 1

Reply