Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- /** * A class for constructing a Decimal-to-Binary Number- Converter; * contains a main method for demonstration. */
- public class Dec2Bin {
- public Stack<Integer> binStack; // We make it public to modify it in our tests.
- private int N;
- /**
- * Constructor of an empty object. Use method {@code convert()} to convert a number.
- */
- public Dec2Bin() {
- binStack = new Stack<>();
- }
- /**
- * Returns the number that is converted as {@code int}.
- *
- * @return the converted number
- */
- public int getN() {
- return N;
- }
- /**
- * Converts the given number into binary format, with each digit being represented in a
- * stack of {@code int}.
- *
- * @param N the number that is to be converted.
- */
- public void convert(int N) {
- // TODO implement this method
- int bin;
- while(N!=0){
- bin = N%2; // 1 oder 0, Rest von Division durch 2, anafangen mit niedrigstem Wert
- N = N/2;
- binStack.push(bin);
- }
- }
- /**
- * Returns the digits that are stored in {@code binStack} as a string. To is the binary format of the
- * converted number.
- * For testing purpose, we require that the function works also, if the variable {@code binStack} is
- * modified externally.
- *
- * @return a string representation of the number in binary format.
- */
- @Override
- public String toString() {
- // Caution: Stack.toString() does NOT respect stack order. Do not use it.
- // TODO implement this method
- // Kopie des Stacks erstellen
- Stack<Integer> copyStack = new Stack<>();
- copyStack.addAll(binStack);
- int size = binStack.size(); //wie viele Elemente vorhanden fuer Iterierung
- String res_str = new String(); //wo wir rueckgabestring lagern
- for (int i = 0; i < size; i++) {
- int bin = copyStack.pop(); //leeren die kopie von unserem stack
- res_str+=bin;
- }
- return res_str;
- }
- public static void main(String[] args) {
- Dec2Bin dec2bin = new Dec2Bin();
- dec2bin.convert(50);
- System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
- // Do it another time to demonstrate that toString does not erase the binStack.
- System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement