//如何将十进制整数转化成二进制和十六进制 public static void main2(String[] args) { //十进制转化成二进制 Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String c = " "; while (n != 0) { int b = n % 2; n = n / 2; c = b + c; } System.out.println(c); }
public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String ret = ""; String c = ""; while (n != 0) { int b = n % 16; switch (b) { case 10: { ret = "A"; break; } case 11: { ret = "B"; break; } case 12: { ret = "C"; break; } case 13: { ret = "D"; break; } case 14: { ret = "E"; break; } case 15: { ret = "F"; break; } default: { ret = "" + b; break; } } n = n / 16; c = ret + c; } System.out.print(c);//这里一定要跳出while循环再打印,否则就会重复 } }
同理,方法是“除16取余,逆序排列”
总结:虽然以上代码不是最简洁的,也并不好用,甚至有点繁琐,但刚开始学,只会用这些简单的逻辑语句去创作,以后会不断改进哒~~
一如既往,欢迎前辈们多多赐教,不胜感激!!!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)