1 //利用棧實現十進制轉換為二進制 2 package classwork9; 3 4 import java.util.Scanner; 5 import java.util.Stack; 6 7 public class Jinzhizhuanhuan { 8 public static int zhuanhuan(int x) { 9 Stack<Integer> a = new Stack<Integer>(); 10 int res = 0; 11 while (x != 0) { 12 a.push(x % 2); 13 x /= 2; 14 } 15 while (!a.empty()) { 16 res = res * 10 + a.peek(); 17 a.pop(); 18 } 19 return res; 20 } 21 22 public static void main(String[] args) { 23 Scanner in=new Scanner(System.in); 24 System.out.println("請輸入一個整數:"); 25 int x=in.nextInt(); 26 System.out.println("其二進制為:"+zhuanhuan(x)); 27 } 28 29 }