2 진수에서 10 진수로

Sep 13 2020

이 코드를 어떻게 든 더 빠르게 만들 수 있고 읽을 수 있습니까? 저는 초보자이고 나중에 Decimal에서 Binary로 변환하는 다른 클래스를 만들 것입니다.하지만 먼저 그 방법을 알아야합니다.

package convert.console.binaryToDecimal;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ConversionProgram {
    //check if number is actually binary
    public static boolean isBin(int numb){
        int inputNumb = numb;

        while(inputNumb > 0){
            if(inputNumb % 10 > 1){
                return false;
            }
            inputNumb /= 10;
        }
        return true;
    }

    public static int binaryToDecimal(int input){

        int number = input;
        int decimalNumber = 0;
        int baseNumber = 1;
        int lastDigit;
        //check if provided number is binary
        if(isBin(number)){
            while(number != 0){

                //takes last digit from input
                lastDigit = number % 10;
                //counts decimal number
                decimalNumber += lastDigit * baseNumber;
                /*every time increase baseNumber by 2
                (base number is 1 ,because when u start from right 2pow0 is always 1)
                 */
                baseNumber *= 2;
                //removes last digit from input
                number /= 10;

            }
        }
        else if(!isBin(number)){
            System.out.println("Wrong!\nProvide binary number - contains only 0 and 1");
        }
        return decimalNumber;
    }

    //check if output is correct
    public static void isCorrect(int bin, int conv){

            if (conv == 0) {
                System.out.println("Try again");
            } else {
                System.out.println("Converted number from binary " + bin + " to decimal is " + conv);
            }
    }



    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Input binary number :");
        try {

            int binaryNumb = input.nextInt();
            int convertedNumb = binaryToDecimal(binaryNumb);
            isCorrect(binaryNumb, convertedNumb);

        }catch(InputMismatchException e){
            System.out.println("Wrong input!");
        }
    }

}
```

답변

2 MiguelAvila Sep 13 2020 at 09:31

코드 서식과 별도로 솔루션에서 지적해야 할 사항이 있습니다. eclipse를 사용하는 경우 ctrl + shift + f를 누르면 코드를 더 쉽게 수정할 수 있습니다.


이진법

  • Java에서 매개 변수로 보내는 값은 다른 함수에 영향을주지 않습니다 (데이터 구조 노드와 같은 일부 예외가 있음). 따라서 inputNumb변수를 저장할 수 있습니다.
  • 가능한 모든 코드를 읽을 수 있도록 변수, 메서드 및 클래스의 이름을 설명합니다. 미래에는 혼자 일하지 않을 것입니다.
    public static boolean isBinary(int number) {
        while (number > 0) {
            if(number % 10 > 1)
                return false;
            number /= 10;
        }
        return true;
    }

Binary To Decimal 방법

  • 변수가 한 번만 사용 ()으로 선언 된 경우 해당 lastDigit변수가 나타나는 위치에 할당 된 값으로 대체합니다.
  • 필요할 때 댓글 작성
  • 프로그램의 올바른 워크 플로를 방해하는 불일치를 발견하면 예외를 발생시킵니다.
  • 부울 조건을 두 번 확인하지 마십시오. if else문이 하나의 조건에만 의존하는 경우 else블록 에서 참이 아닌지 확인하지 않은 경우 중복 else되며 조건이 if실패 할 때 실행됩니다.
    public static int binaryToDecimal(int number) {
        int decimalNumber = 0;
        int powerOfTwo = 1; //renamed, gives more context
        if (isBinary(number)) {
            while (number != 0) {
                decimalNumber += (number % 10) * powerOfTwo;
                powerOfTwo *= 2;
                number /= 10; //removes the last digit
            }
        } else throw new InvalidParameterException("Not a binary number");
        return decimalNumber;
    }

이 isCorrect메서드는 한 번 사용되므로 생략 할 수 있습니다.

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a binary number: ");
        try {
            int binaryNumb = input.nextInt();
            int convertedNumb = binaryToDecimal(binaryNumb);
            System.out.println("The number "+ binaryNumb + " was converted to decimal," +
                    "\nthe result was: " + convertedNumb);
        } catch (InputMismatchException e) {
            System.out.println("Wrong input!");
        }
    }

당신에게 도움이 되었으면합니다.

2 tinstaafl Sep 13 2020 at 21:36

한 가지는 눈치 챘습니다. 내 생각에 이진수는 일반적으로 0과 1 만있는 정수가 아닌 숫자 (string, char [], byte [] 등) 모음으로 표현됩니다. 이 접근 방식은 더 일반적 일뿐만 아니라 숫자가 이미 분리되어 있기 때문에 알고리즘을 상당히 단순화합니다.

고려해야 할 또 다른 측면은 정수는 자릿수로 제한되는 반면 이진수는 일반적으로 32, 64 또는 128 비트를 가질 수 있다는 것입니다.