十进制到二进制而不使用内置函数(如parseInt,Math.pow)等

时间:2015-09-28 01:27:29

标签: java

我需要创建一个程序来获取输入并将其转换为二进制输出。我不能使用内置函数,如(parseInt,Math.pow等)来做到这一点。我被困住了,需要帮助。这就是我到目前为止,分布在两个java文件中。

驱动程序类:

import java.util.*;

public class Driver {

    public Driver(){

    }

    public static void main(String[] args) {

        Driver drive = new Driver();

        // scanner to read in data from the user
        Scanner scanner = new Scanner(System.in);

        // instance of the solver class
        Solver mySolver = new Solver();

        // read in the first number
        System.out.print("Enter a number to convert to binary: ");
        char [] val1 = scanner.nextLine().toCharArray();

        // call solver class method to obtain the number of bits
        int numBits = mySolver.howManyBits(val1);

        // use the number of bits and the input to get the binary representation 
        char [] binaryVal1 = mySolver.stringToBinary(val1, numBits);

        // print the results
        System.out.println(new String(binaryVal1));

        // read in the arithmetic expression
        System.out.print("Enter an arithmetic expression to convert to binary: ");
        char [] val2 = scanner.nextLine().toCharArray();

        // call the solver class to solve the expression
        char [] result2 = mySolver.solveExpression(val2);

        // print the results
        System.out.println(new String(result2));

        scanner.close();
    }

}

解算器类:

import java.util.*;

public class Solver{

    private int[] powersOf2;

    public Solver() {
        // Constructor method 
        int numPowersOf2 = 16;
        powersOf2 = new int[numPowersOf2];
        int exponent=1;

        for(int count = 1; count <= numPowersOf2; count++){
            exponent *= 2;
            powersOf2[count] = exponent;
        } 
    }

    public static void main(String[] args) {
        // Main method for Solver class
        Solver solve = new Solver();
    }

    public int howManyBits(char[] val1) {
        // howManyBits method

        int decimal = Integer.parseInt(new String(val1));
        int logValue = (int) (Math.log(decimal)/Math.log(2));
        int numBits = 0;

        // Condition block to return number of bits.

        if (logValue <= 3) {
            numBits = 4;
        }
        else if (logValue <=7 && logValue > 3) {
            numBits = 8;
        }
        else if (logValue <=15 && logValue > 7) {
            numBits = 16;
        }

        System.out.println("Bits: " + numBits);

        return numBits;
    }

    public char[] stringToBinary(char[] val1, int numBits) {
        // stringToBinary method

        int decimalNumber = Integer.parseInt(new String(val1));
        char[] binaryVal1 = new char[numBits];

        int remainder = 0;

        for (int count = 0; decimalNumber > 0; count++) {

            remainder = decimalNumber % 2;  
            decimalNumber /= 2;
            char[] place = String.valueOf(remainder).toCharArray();
            binaryVal1[count] = place[count];
            System.out.println(binaryVal1[count]);
        }

        return binaryVal1;
    }

    public char[] twosComplement(char[] val1){
        return val1;

    }

    public char[] solveExpression(char[] val2) {
        // solveExpression method
        return null;
    }

}

2 个答案:

答案 0 :(得分:0)

现在我很担心你的意思是&#34;内置函数&#34;。在那种情况下,其中一个是println吗?还是Scanner.nextInt?我认为&#34;内置函数&#34;不是很清楚。我认为它可能意味着具有单词int的函数。

我的想法是你不断地将十进制数除以2并存储余数。然后以相反的顺序显示余数。这意味着您可能会使用Stack。这是我能想到的最佳方法:

Stack<Integer> remainders = new Stack<> ();
Scanner s = new Scanner (System.in);
int decimalNumber = s.nextInt();

while (decimalNumber >= 2) {
    remainders.push(decimalNumber % 2);
    decimalNumber /= 2;
}

remainders.push(decimalNumber);

StringBuilder builder = new StringBuilder ();
int size = remainders.size();
for (int i = 0 ; i < size ; i++) {
    builder.append(remainders.pop());
}

System.out.println(builder);

P.S。从技术上讲,函数是不在ny类中的例程。方法必须在一个类中。这意味着在这种情况下,您可以使用Integer.toBinaryString

开玩笑,我知道你的意思。

答案 1 :(得分:0)

如果你已经了解了位操作,那么你可以通过二进制AND与1(x & 1)找到最右边的位,然后使用无符号右移运算符右移这个值({{ 1}}),并继续这样做,直到数字为0 请参阅Oracle Java教程Bitwise and Bit Shift Operators或Wikipedia Bitwise operation

根据您是否被允许使用x >>> 1类,以下是两个版本:

StringBuilder

当然,您首先必须将字符串解析为整数,这很简单:

// Using StringBuilder
public static String toBinary(int number) {
    StringBuilder buf = new StringBuilder();
    do {
        buf.append((number & 1) == 0 ? '0' : '1');
        number >>>= 1;
    } while (number != 0);
    return buf.reverse().toString();
}

// Using character array
public static String toBinary(int number) {
    char[] buf = new char[32];
    int i = buf.length;
    do {
        buf[--i] = (number & 1) == 0 ? '0' : '1';
        number >>>= 1;
    } while (number != 0);
    return new String(buf, i, buf.length - i);
}

然后你可以将它们组合起来:

public static int toInt(String text) {
    if (text.isEmpty())
        throw new IllegalArgumentException();
    int num = 0;
    for (char c : text.toCharArray()) {
        if (c < '0' || c > '9')
            throw new IllegalArgumentException();
        num = num * 10 + c - '0';
    }
    return num;
}