从Base 10转换到Base 2

时间:2017-04-06 02:56:24

标签: java binary converter

我正在尝试将基数10中的数字转换为基数2中的数字,但我遇到了问题。当我运行代码时,我得到错误顺序的基数为2的数字。例如,我输入54并获得110110而不是011011,这是正确的值。

import java.util.Scanner; 
public class DecimalToBinary
{
public static void main(String arg[]){   
  int quotient;
  int remainder;

  Scanner keyboard = new Scanner (System.in);
  System.out.println("Please enter a decimal number:"); 
  quotient = keyboard.nextInt();  

  do {
     remainder = quotient % 2;
     quotient = quotient / 2;

    // String x = String.valueOf(remainder);
    // System.out.print(x);
  System.out.print (remainder);

  } while (quotient != 0);
   }  
   }

5 个答案:

答案 0 :(得分:1)

Base 10到Base 2应该反向输出,我想你可以使用array,然后反向输出array

 public static void main(String arg[]){
        int quotient;
        int remainder;
        List<Integer> arrayList=new ArrayList<Integer>();
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter a decimal number:");
        quotient = keyboard.nextInt();

        do {
            remainder = quotient % 2;
            quotient = quotient / 2;

            // String x = String.valueOf(remainder);
            // System.out.print(x);
           // System.out.print (remainder);
            arrayList.add(remainder);

        } while (quotient != 0);
        ListIterator<Integer> li;
        for (li = arrayList.listIterator(); li.hasNext();) {// 将游标定位到列表结尾
            li.next();
        }
        for (; li.hasPrevious();) {// 逆序输出列表中的元素
            System.out.print(li.previous() + " ");
        }
    }

答案 1 :(得分:1)

Java有一个内置的方法来执行此操作:

i

,其中

  • radix是您的基数十,
  • dbo.sp_getOrders dbo.sp_getOrders_xyz123 是您想要的基础,在您的情况下,2。

它将以二进制形式返回一个字符串。

答案 2 :(得分:1)

另一个内置的java函数是

{{1}}

其中num是您要转换的基数10

答案 3 :(得分:0)

尝试这个解决方案,很简单:

  int quotient;
      int remainder;

      Scanner keyboard = new Scanner (System.in);
      System.out.println("Please enter a decimal number:"); 
      quotient = keyboard.nextInt();  
      Stack<Integer> s=new Stack<Integer>();
      do {
         remainder = quotient % 2;
         quotient = quotient / 2;
         s.add(remainder);
        // String x = String.valueOf(remainder);
        // System.out.print(x);
      //System.out.print (remainder);
      } while (quotient != 0);
      while(!s.isEmpty()){
          System.out.print(s.pop());

      }

答案 4 :(得分:-1)

我能够修复您的代码

public class CustomDecimalToBinary {
    public static void Dec2Bin() {
        int quotient;
        int remainder;

        Scanner keyboard = new Scanner (System.in);
        System.out.println("Please enter a decimal number:");
        quotient = keyboard.nextInt();

        do {
            remainder = quotient % 2;

            // String x = String.valueOf(remainder);
            // System.out.print(x);
            System.out.print (remainder);

        } while ((quotient /= 2) != 0);
    }
}

示例输出:

Please enter a decimal number:
54
011011

编辑:看来我解决了问题,得到了你想要的输出,但你的代码产生了正确的输出......