#include<iostream> #include<stack> using namespace std; int main() { stack<int> s; int num, r; cout<<"Enter a number"<<endl; cin>>num; cout<<"The binary code of "<<num<<" is "; while(num !=0 ) { r = num % 2; num = num / 2; s.push(r); } while(!s.empty()) { cout<<s.top(); s.pop(); } cout<<endl; system("pause"); return 0; }
|
|
import java.util.Stack; import java.util.Scanner; public class ApplyStack { public static void main(String [] args) { Scanner input = new Scanner(System.in); Stack<Integer> s = new Stack<Integer>(); StringBuilder bin = new StringBuilder(); int num, r; System.out.println("Enter a number to be converted to binary:"); num = input.nextInt(); System.out.printf("The binary code of %d is ",num); while(num != 0) { r = num % 2; num /= 2; s.push(r); } while(!s.empty()) { bin.append(s.pop()); } System.out.println(bin); } } |