一题用switch写的感觉好麻烦啊
Topic source#改进了一下用map不过还是觉得麻烦
package Practice;
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 m = new LinkedList<>();
Integer n2 = (Integer) n;
Map<Integer,String> m2 = new HashMap<>();
m2.put(10,"A");
m2.put(11,"B");
m2.put(12,"C");
m2.put(13,"D");
m2.put(14,"E");
m2.put(15,"F");
String s="";
while(n>=16) {
if(n%16>=10) {
m.push(m2.get(n%16));
}
else {
m.push(n%16);
}
n=n/16;
}
m.push(n);
while(!m.isEmpty()) {
s = s+ m.pop().toString();
}
System.out.print(s);
return s;
}
}
- 1
银发的index
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 m = new LinkedList<>();
String s="";
while(n>=16) {
switch(n%16) {
case 10:
m.push("A");
break;
case 11:
m.push("B");
break;
case 12:
m.push("C");
break;
case 13:
m.push("D");
break;
case 14:
m.push("E");
break;
case 15:
m.push("F");
break;
default:
m.push(n%16);
}
n=n/16;
}
m.push(n);
while(!m.isEmpty()) {
s = s+ m.pop().toString();
}
System.out.print(s);
return s;
}
}