简体   繁体   English

不使用数组将十进制数转换为二进制数

[英]Convert Decimal Number to Binary without using Array

I want to make a java code that converts any decimal number inputted, into binary number.我想制作一个 java 代码,将输入的任何十进制数转换为二进制数。 Although the array method is easy, it doesn't actually prints a number(it prints array), nor does it seem to correctly use the algorithm we use manually.虽然数组方法很简单,但它实际上并没有打印一个数字(它打印的是数组),它似乎也没有正确使用我们手动使用的算法。 So I'm trying to do it without array.所以我试图在没有数组的情况下做到这一点。 The problem is it sometimes giving correct answers, and sometimes giving wrong answers.问题是它有时给出正确答案,有时给出错误答案。 I think the problem might be in multiplying by zero in the last cycle of loop, but I'm not sure.我认为问题可能出在循环的最后一个周期中乘以零,但我不确定。 The code I wrote as comment was a failed try to resolve the issue.我作为评论写的代码是解决问题的失败尝试。

import java.util.Scanner;

public class DecToBin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long dec = 0, num = 0, rem = 0;
        
        System.out.print("Enter A Decimal Number: ");
        dec = sc.nextLong();
        while(dec > 0){
            rem = dec % 2;
            num += rem;
            num *= 10;
            dec /= 2;

        }
        // if(num % 100 == 10){
        //     num = num/10;
        // }
        System.out.println("Binary Equivalent: " + num);


    }
}
 

This is my first time answering, so please let me know if anything is off:-)这是我第一次回答,所以如果有任何问题请告诉我:-)

You could try to use a String as intermediate.您可以尝试使用 String 作为中间体。 Short and simple.... But i dont know if that counts as an Array:-)简短而简单......但我不知道这是否算作一个数组:-)
Your while-part would be something like this:您的 while-part 将是这样的:

    String strBin = "";
    while(dec > 0){
        strBin = String.valueOf(dec%2) + strBin;
        dec /= 2;
    }
    num = Long.valueOf(strBin);        

The order of bits in the binairy number is correct by adding in front of the previous String, so building up the result from right to left.通过在前一个 String 前面添加,二进制数中的位顺序是正确的,因此从右到左构建结果。
Also, i would not use a Long (last line... num), because it limits your max result.另外,我不会使用 Long(最后一行......数字),因为它限制了你的最大结果。 But if you must..... meh但如果你必须......嗯

This problem lends its self to a recursive solution这个问题适用于递归解决方案

  private static int DecToBin(final int input, final int result) {
    if (input == 0) {
      return result;
    }
    return DecToBin(input / 2, result * 10 + input % 2);
  }

I found following "direct" issues with your code:我发现您的代码存在以下“直接”问题:

  1. You are not reversing the final number.您没有反转最终数字。 In the manual way of converting DEC->BIN, we reverse the final representation.在手动转换 DEC->BIN 的方式中,我们反转最终的表示。 Hint: Dry run for input 11提示:输入 11 的空运行
  2. You are doing num += rem; num *= 10你在做num += rem; num *= 10 num += rem; num *= 10 . num += rem; num *= 10 The order is wrong.顺序错了。 You should be multiplying it before you add the remainder.在添加余数之前,您应该先乘以它。 eg.例如。 Your code will output 1010 for 5 , instead of 101 .您的代码将 output 1010用于5 ,而不是101
  3. By your method, you are trying to represent decimal number into its binary representation as int , which limits your input to 2047 , as 2048 and above need 11+ digits for their binary representation and you can't have that in int .通过您的方法,您试图将十进制数表示为其二进制表示形式,如int ,这将您的输入限制为2047 ,因为2048及以上需要 11+ 位的二进制表示,而您不能在int中使用它。 You should use String if you don't want to use array.如果不想使用数组,则应使用String Also, reversing would be easier.另外,倒车会更容易。

something like:就像是:

import java.util.Scanner;

public class DecToBin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int dec = 0, num = 0;
        
        System.out.print("Enter A Decimal Number: ");
        dec = sc.nextInt();
        String bi = "";
        while(dec > 0){
            int rem = dec % 2;
            // num *= 10;
            // num += rem;
            bi += Character.toString(rem + 48);
            dec /= 2;

        }
        // if(num % 100 == 10){
        //     num = num/10;
        // }
        System.out.println("Binary Equivalent: " + new StringBuilder(bi).reverse().toString());


    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM