在二进制表示中反转一个整数

huangapple go评论89阅读模式
英文:

Reversing an integer in binary representation

问题

我尝试创建了一个Java代码,用于接收一个整数,并将其以二进制形式输出。问题似乎在于二进制输出是颠倒的。例如,6 应该输出为 011,但输出为 110

import java.util.Scanner;

public class LabProgram {
  public static void main(String[] args) {

    int userNum;

    Scanner in = new Scanner(System.in);

    userNum = in.nextInt();

    binary(userNum);
    System.out.print("\n");
  }

  private static void binary(int userNum) {
    int remainder;

    while (userNum > 0) {
      remainder = userNum % 2;
      System.out.print(remainder);
      userNum = userNum / 2;
    }
  }
}

我尝试将推入栈的方法结合到代码中,以便将余数推入稍后可以取出的堆栈中,但是无法使其正常运行。

private static void reverse(int userNum) {

  Stack<Integer> backwards = new Stack<>();

  while (userNum > 0) {
    backwards.push(userNum % 2);
    userNum = userNum / 2;
  }

  while (!backwards.isEmpty()) {
    System.out.print(backwards.pop());
  }
}

这是一个课堂作业的一部分,要求如下:

编写一个程序,接受一个正整数作为输入,并输出表示该整数的二进制数的字符串。对于整数 x,算法如下:

只要 x 大于 0
   输出 x % 2(余数为 0 或 1)
   x = x / 2

注意:上述算法以相反的顺序输出 0 和 1。

例如:如果输入为:

6

输出为:

011

6 的二进制表示为 110;算法以相反的顺序输出位。

以下是程序应用的测试和我的结果。

输入 6

你的输出 binary is:110

预期输出 011

输入 19

你的输出 10011

预期输出 11001

输入 255

你的输出 11111111

预期输出 11111111

如果需要任何帮助或指导,请随时告诉我。

英文:

I tried to create a code to take in a whole number in Java and output it in binary. The problem would seem that the binary is printing out backward. For instance, 6 should output as 011 but comes out as 110.

import java.util.Scanner;

public class LabProgram {
  public static void main(String[] args) {

    int userNum;

    Scanner in =new Scanner(System. in );

    userNum = in.nextInt();

    binary(userNum);
    System.out.print(&quot;\n&quot;);
  }

  private static void binary(int userNum) {
    int remainder;

    while (userNum &lt;= 1) {
      System.out.print(userNum);
      return;
    }

    remainder = userNum % 2;
    binary(userNum &gt;&gt; 1);
    System.out.print(remainder);
  }
}

I tried incorporating a push stack to push the remainder into a stack that I can pull later, but couldn't quite get it to land.

private static void reverse(int userNum) {

  String backwards;

  while (userNum &gt;= 0) {
    backwards.push(int userNum);
    System.out.println(backwards);
    return;
  }
}

It is part of a class assignment which asks the following.

> Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:

As long as x is greater than 0
   Output x % 2 (remainder is either 0 or 1)
   x = x / 2

Note: The above algorithm outputs the 0's and 1's in reverse order.

Ex: If the input is:

6

the output is:

011

6 in binary is 110; the algorithm outputs the bits in reverse.

These are the tests the program applies and my results.

Input 6

Your output binary is:110

Expected output 011

Input 19

Your output 10011

Expected output 11001

Input 255

Your output 11111111

Expected output 11111111

Any help or guidance in this, I would be greatly appreciative of it.

答案1

得分: 1

根据要求,并不考虑负数:

import java.util.Scanner;

public class LabProgram {
    public static void main(String[] args) {
        int userNum;

        Scanner scnr = new Scanner(System.in);

        userNum = scnr.nextInt();

        while(userNum > 0){
            System.out.print(userNum % 2);
            userNum = userNum / 2;
        }
        System.out.print("\n");
    }
}
英文:

Per the requirement and not taking into consideration of negative numbers

import java.util.Scanner;

public class LabProgram {
    public static void main(String[] args) {
        int userNum;

        Scanner scnr = new Scanner(System.in);

        userNum = scnr.nextInt();

        while(userNum &gt; 0){
            System.out.print(userNum % 2);
            userNum = userNum / 2;
        }
        System.out.print(&quot;\n&quot;);
    }
}

答案2

得分: 0

首先使用预定义方法,然后使用自定义方法。

public class IntToBinary {

	public static void main(String[] args) {
		int decimalNumber = 10;

		System.out.println(Integer.toBinaryString(decimalNumber));

		System.out.println(convertBinary(10));
	}

	public static String convertBinary(int num) {
		StringBuilder sb = new StringBuilder();
		int binary[] = new int[40];
		int index = 0;
		while (num > 0) {
			binary[index++] = num % 2;
			num = num / 2;
		}
		for (int i = index - 1; i >= 0; i--) {
			sb.append(binary[i]);
		}
		return sb.toString();
	}

}
英文:

First using predefined method then a custom one.

public class IntToBinary {

	public static void main(String[] args) {
		int decimalNumber = 10;

		System.out.println(Integer.toBinaryString(decimalNumber));

		System.out.println(convertBinary(10));
	}

	public static String convertBinary(int num) {
		StringBuilder sb = new StringBuilder();
		int binary[] = new int[40];
		int index = 0;
		while (num &gt; 0) {
			binary[index++] = num % 2;
			num = num / 2;
		}
		for (int i = index - 1; i &gt;= 0; i--) {
			sb.append(binary[i]);
		}
		return sb.toString();
	}

}

答案3

得分: 0

你的程序在处理正数时似乎工作正常。然而,它不能处理负数,负数有其独特的二进制表示,称为二进制补码。你可以像下面这样进行一些调整:

private static void binary(int userNum) {
    int remainder;

   //  while (userNum <= 1) {
   //     System.out.print(userNum);
   //     return;
   // }
   if (userNum == 0) {
          return;
    }

    // 直接通过按位与操作屏蔽位,而不是除以二
    remainder = userNum & 1;
    // 然后通过符号位向右移位
    binary(userNum >>> 1);
    System.out.print(remainder);    
}
}

binary(-6));

输出:

11111111111111111111111111111010

这些数字之所以以正确的顺序打印出来,是因为你的递归函数。从递归过程中打印出栈中存储的值,这是一种自然的行为。

英文:

Your program appears to work fine for positive values. However it does not handle negative numbers which have their own unique binary representation known as two's complement. You could do something like the following to accommodate:

private static void binary(int userNum) {
    int remainder;

   //  while (userNum &lt;= 1) {
   //     System.out.print(userNum);
   //     return;
   // }
   if (userNum == 0) {
          return;
    }

    // simply mask off the bit instead of dividing by two
    remainder = userNum &amp; 1;
    // and shift right thru the sign bit
    binary(userNum &gt;&gt;&gt; 1);
    System.out.print(remainder);    
}
}

binary(-6));

prints

11111111111111111111111111111010

And the reason these printed out in proper order is because your routine is recursive. That is a natural behavior of printing the values stored in the stack from a recursive procedure.

答案4

得分: -1

import java.util.Scanner;

public class Reverse_BinaryNum {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        int inputNum;

        System.out.println("输入数字:");
        inputNum = scnr.nextInt();

        System.out.println("给定数字的反向二进制表示为:");
        while (inputNum > 0) {
            System.out.print(inputNum % 2);
            inputNum = inputNum / 2;
        }
        scnr.close();
    }
}
英文:
import java.util.Scanner;

public class Reverse_BinaryNum {

    public static void main(String[] args) {
        /* Type your code here. */

        Scanner scnr = new Scanner(System.in);

        int inputNum;

        System.out.println(&quot;Enter the Digit : &quot;);
        inputNum = scnr.nextInt();

        System.out.println(&quot;The Reverse Binary for the given Digit is : &quot;);
        while (inputNum &gt; 0) {
            System.out.print(inputNum % 2);
            inputNum = inputNum / 2;

        }
        scnr.close();
    }
}

huangapple
  • 本文由 发表于 2020年10月10日 23:52:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64295338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定