import java.util.*; /** * completeStack * 利用Stack把一个给定的整数转换为十六进制 */ public class completeStack { 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) { // 建栈 Stack<Character> stack = new Stack<>(); // 压栈 while(n!=0) { int saveNum = n % 16; char saveChar; if(saveNum > 9) { saveChar = (char)('A' + saveNum % 10); } else { saveChar = (char)(saveNum + '0'); } stack.push(saveChar); n = n / 16; } // 弹栈 String returStr = ""; while(!stack.isEmpty()) { returStr += stack.pop(); } return returStr; } }
Sign in to make a reply
细水静流