[英]Converting Decimal to Binary Java
我正在嘗試使用 Java 將用戶輸入的十進制數轉換為二進制數。
我收到錯誤。
package reversedBinary;
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(number));
}
}
private static Object binaryform(int number) {
int remainder;
if (number <=1) {
System.out.print(number);
}
remainder= number %2;
binaryform(number >>1);
System.out.print(remainder);
{
return null;
} } }
如何在 Java 中將十進制轉換為二進制?
Integer.toBinaryString()
是一個內置的方法,會做得很好。
Integer.toString(n,8) // decimal to octal
Integer.toString(n,2) // decimal to binary
Integer.toString(n,16) //decimal to Hex
其中 n = 十進制數。
您的binaryForm
方法陷入無限遞歸,如果number <= 1
,您需要返回:
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number = in.nextInt();
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
System.out.print("Convert to binary is:");
//System.out.print(binaryform(number));
printBinaryform(number);
}
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number % 2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
我只想補充一下,對於任何使用過的人:
String x=Integer.toBinaryString()
獲取一個二進制數字字符串,並希望將該字符串轉換為 int。 如果你使用
int y=Integer.parseInt(x)
您將收到 NumberFormatException 錯誤。
我所做的將字符串 x 轉換為整數,首先將字符串 x 中的每個單獨的 Char 轉換為 for 循環中的單個 Char。
char t = (x.charAt(z));
然后我將每個字符轉換回一個單獨的字符串,
String u=String.valueOf(t);
然后將每個字符串解析為一個整數。
Id figure Id 發布此信息,因為我花了一段時間才弄清楚如何將二進制文件(例如 01010101)轉換為整數形式。
/**
* @param no
* : Decimal no
* @return binary as integer array
*/
public int[] convertBinary(int no) {
int i = 0, temp[] = new int[7];
int binary[];
while (no > 0) {
temp[i++] = no % 2;
no /= 2;
}
binary = new int[i];
int k = 0;
for (int j = i - 1; j >= 0; j--) {
binary[k++] = temp[j];
}
return binary;
}
public static void main(String h[])
{
Scanner sc=new Scanner(System.in);
int decimal=sc.nextInt();
String binary="";
if(decimal<=0)
{
System.out.println("Please Enter more than 0");
}
else
{
while(decimal>0)
{
binary=(decimal%2)+binary;
decimal=decimal/2;
}
System.out.println("binary is:"+binary);
}
}
以下將十進制轉換為具有時間復雜度的二進制:O(n) 線性時間並且沒有任何 java 內置函數
private static int decimalToBinary(int N) {
StringBuilder builder = new StringBuilder();
int base = 2;
while (N != 0) {
int reminder = N % base;
builder.append(reminder);
N = N / base;
}
return Integer.parseInt(builder.reverse().toString());
}
如果要反轉計算的二進制形式,可以使用 StringBuffer 類並只需使用 reverse() 方法。 這是一個示例程序,將解釋其使用並計算二進制
public class Binary {
public StringBuffer calculateBinary(int number) {
StringBuffer sBuf = new StringBuffer();
int temp = 0;
while (number > 0) {
temp = number % 2;
sBuf.append(temp);
number = number / 2;
}
return sBuf.reverse();
}
}
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("enter the number you want to convert");
BufferedReader bReader = new BufferedReader(newInputStreamReader(System.in));
int number = Integer.parseInt(bReader.readLine());
Binary binaryObject = new Binary();
StringBuffer result = binaryObject.calculateBinary(number);
System.out.println(result);
}
}
這可能看起來很傻,但如果你想嘗試效用函數
System.out.println(Integer.parseInt((Integer.toString(i,2))));
必須有一些實用方法可以直接做到這一點,我不記得了。
在 C# 中,但它與在 Java 中相同:
public static void findOnes2(int num)
{
int count = 0; // count 1's
String snum = ""; // final binary representation
int rem = 0; // remainder
while (num != 0)
{
rem = num % 2; // grab remainder
snum += rem.ToString(); // build the binary rep
num = num / 2;
if (rem == 1) // check if we have a 1
count++; // if so add 1 to the count
}
char[] arr = snum.ToCharArray();
Array.Reverse(arr);
String snum2 = new string(arr);
Console.WriteLine("Reporting ...");
Console.WriteLine("The binary representation :" + snum2);
Console.WriteLine("The number of 1's is :" + count);
}
public static void Main()
{
findOnes2(10);
}
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
System.out.print("Put a number : ");
int a=in.nextInt();
StringBuffer b=new StringBuffer();
while(a>=1)
{
if(a%2!=0)
{
b.append(1);
}
else if(a%2==0)
{
b.append(0);
}
a /=2;
}
System.out.println(b.reverse());
}
您的所有問題都可以用一個班輪解決! 要將我的解決方案合並到您的項目中,只需刪除您的binaryform(int number)
方法,並替換System.out.print(binaryform(number));
與System.out.println(Integer.toBinaryString(number));
.
不使用 Integer.ParseInt() 的二進制到十進制:
import java.util.Scanner;
//convert binary to decimal number in java without using Integer.parseInt() method.
public class BinaryToDecimalWithOutParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
int binarynum =input.nextInt();
int binary=binarynum;
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
System.out.println("Binary="+binarynum+" Decimal="+decimal); ;
}
}
輸出:
輸入一個二進制數:
1010
二進制=1010 十進制=10
使用 Integer.parseInt() 將二進制轉換為十進制:
import java.util.Scanner;
//convert binary to decimal number in java using Integer.parseInt() method.
public class BinaryToDecimalWithParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
String binaryString =input.nextLine();
System.out.println("Result: "+Integer.parseInt(binaryString,2));
}
}
輸出:
輸入一個二進制數:
1010
結果:10
一個相當簡單而不是高效的程序,但它可以完成工作。
Scanner sc = new Scanner(System.in);
System.out.println("Give me my binaries");
int str = sc.nextInt(2);
System.out.println(str);
public static String convertToBinary(int dec)
{
String str = "";
while(dec!=0)
{
str += Integer.toString(dec%2);
dec /= 2;
}
return new StringBuffer(str).reverse().toString();
}
/**
* converting decimal to binary
*
* @param n the number
*/
private static void toBinary(int n) {
if (n == 0) {
return; //end of recursion
} else {
toBinary(n / 2);
System.out.print(n % 2);
}
}
/**
* converting decimal to binary string
*
* @param n the number
* @return the binary string of n
*/
private static String toBinaryString(int n) {
Stack<Integer> bits = new Stack<>();
do {
bits.push(n % 2);
n /= 2;
} while (n != 0);
StringBuilder builder = new StringBuilder();
while (!bits.isEmpty()) {
builder.append(bits.pop());
}
return builder.toString();
}
或者你可以使用Integer.toString(int i, int radix)
例如:(將 12 轉換為二進制)
Integer.toString(12, 2)
實際上,您可以將其編寫為遞歸函數。 每個函數調用都返回它們的結果並添加到前一個結果的尾部。 可以使用 java 編寫此方法,如下所示:
public class Solution {
private static String convertDecimalToBinary(int n) {
String output = "";
if (n >= 1) {
output = convertDecimalToBinary(n >> 1) + (n % 2);
}
return output;
}
public static void main(String[] args) {
int num = 125;
String binaryStr = convertDecimalToBinary(num);
System.out.println(binaryStr);
}
}
讓我們看看上面的遞歸是如何工作的:
調用一次 convertDecimalToBinary 方法后,它會調用自己,直到數字的值小於 1,並將所有連接的結果返回到它首先調用的地方。
參考:
Java - 按位和位移運算符https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
更好的方法:
public static void main(String [] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine().trim());
double ans = 0;
int i=0;
while(t!=0){
int digit = t & 1;
ans = ans + (digit*Math.pow(10,i));
i++;
t =t>>1;
}
System.out.println((int)ans);
}
public class BinaryConvert{
public static void main(String[] args){
System.out.println("Binary Result: "+ doBin(45));
}
static String doBin(int n){
int b = 2;
String r = "";
String c = "";
do{
c += (n % b);
n /= b;
}while(n != 0);
for(int i = (c.length() - 1); i >=0; i--){
r += c.charAt(i);
}
return r;
}
}
我自己剛剛解決了這個問題,我想分享我的答案,因為它包括二進制反轉,然后轉換為十進制。 我不是一個非常有經驗的編碼員,但希望這對其他人有幫助。
我所做的是在轉換二進制數據時將其推入堆棧,然后將其彈出以反轉它並將其轉換回十進制。
import java.util.Scanner;
import java.util.Stack;
public class ReversedBinary
{
private Stack<Integer> st;
public ReversedBinary()
{
st = new Stack<>();
}
private int decimaltoBinary(int dec)
{
if(dec == 0 || dec == 1)
{
st.push(dec % 2);
return dec;
}
st.push(dec % 2);
dec = decimaltoBinary(dec / 2);
return dec;
}
private int reversedtoDecimal()
{
int revDec = st.pop();
int i = 1;
while(!st.isEmpty())
{
revDec += st.pop() * Math.pow(2, i++);
}
return revDec;
}
public static void main(String[] args)
{
ReversedBinary rev = new ReversedBinary();
System.out.println("Please enter a positive integer:");
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
{
int input = Integer.parseInt(sc.nextLine());
if(input < 1 || input > 1000000000)
{
System.out.println("Integer must be between 1 and 1000000000!");
}
else
{
rev.decimaltoBinary(input);
System.out.println("Binary to reversed, converted to decimal: " + rev.reversedtoDecimal());
}
}
}
}
你可以使用Wrapper Classes的概念直接將十進制轉換為二進制,十六進制和八進制.Below是一個非常簡單的程序,可以將十進制轉換為反向二進制。希望它有助於你的java知識
public class decimalToBinary
{
public static void main(String[] args)
{
int a=43;//input
String string=Integer.toBinaryString(a); //decimal to binary(string)
StringBuffer buffer = new StringBuffer(string); //string to binary
buffer.reverse(); //reverse of string buffer
System.out.println(buffer); //output as string
}
}
import java.util.*;
public class BinaryNumber
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number");
int n = scan.nextInt();
int rem;
int num =n;
String str="";
while(num>0)
{
rem = num%2;
str = rem + str;
num=num/2;
}
System.out.println("the bunary number for "+n+" is : "+str);
}
}
這是一個非常基本的程序,我是在將一般程序寫在紙上之后得到的。
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number:");
int number = input.nextInt();
while(number!=0)
{
if(number%2==0)
{
number/=2;
System.out.print(0);//Example: 10/2 = 5 -> 0
}
else if(number%2==1)
{
number/=2;
System.out.print(1);// 5/2 = 2 -> 1
}
else if(number==2)
{
number/=2;
System.out.print(01);// 2/2 = 0 -> 01 ->0101
}
}
}
}
//converts decimal to binary string
String convertToBinary(int decimalNumber){
String binary="";
while(decimalNumber>0){
int remainder=decimalNumber%2;
//line below ensures the remainders are reversed
binary=remainder+binary;
decimalNumber=decimalNumber/2;
}
return binary;
}
最快的解決方案之一:
public static long getBinary(int n)
{
long res=0;
int t=0;
while(n>1)
{
t= (int) (Math.log(n)/Math.log(2));
res = res+(long)(Math.pow(10, t));
n-=Math.pow(2, t);
}
return res;
}
使用 StringBuilder 在正在構造的十進制字符串前使用 insert() 效果更好,無需調用 reverse(),
static String toBinary(int n) {
if (n == 0) {
return "0";
}
StringBuilder bldr = new StringBuilder();
while (n > 0) {
bldr = bldr.insert(0, n % 2);
n = n / 2;
}
return bldr.toString();
}
好吧,你可以像這樣使用while循環,
import java.util.*;
public class DecimalToBinaryDemo
{
// this function converts decimal to binary
static void toBinary(int num)
{
// here we are storing binary number
int binaryNumber[] = new int[1000];
// "count" variable is counter for binary array
int count = 0;
while(num > 0)
{
// storing remainder in binary array
binaryNumber[count] = num % 2;
num = num / 2;
count++;
}
// here we are printing binary in reverse order
for(int a = count - 1; a >= 0; a--)
System.out.print(binaryNumber[a]);
}
public static void main(String[] args)
{
int number = 20;
toBinary(number);
}
}
輸出: 10100
不需要任何 Java 內置函數。 簡單的遞歸就可以了。
public class DecimaltoBinaryTest {
public static void main(String[] args) {
DecimaltoBinary decimaltoBinary = new DecimaltoBinary();
System.out.println("hello " + decimaltoBinary.convertToBinary(1000,0));
}
}
class DecimaltoBinary {
public DecimaltoBinary() {
}
public int convertToBinary(int num,int binary) {
if (num == 0 || num == 1) {
return num;
}
binary = convertToBinary(num / 2, binary);
binary = binary * 10 + (num % 2);
return binary;
}
}
這是十進制到二進制的三種不同方式的轉換
import java.util.Scanner;
public static Scanner scan = new Scanner(System.in);
public static void conversionLogical(int ip){ ////////////My Method One
String str="";
do{
str=ip%2+str;
ip=ip/2;
}while(ip!=1);
System.out.print(1+str);
}
public static void byMethod(int ip){ /////////////Online Method
//Integer ii=new Integer(ip);
System.out.print(Integer.toBinaryString(ip));
}
public static String recursion(int ip){ ////////////Using My Recursion
if(ip==1)
return "1";
return (DecToBin.recursion(ip/2)+(ip%2));
}
public static void main(String[] args) { ///Main Method
int ip;
System.out.println("Enter Positive Integer");
ip = scan.nextInt();
System.out.print("\nResult 1 = ");
DecToBin.conversionLogical(ip);
System.out.print("\nResult 2 = ");
DecToBin.byMethod(ip);
System.out.println("\nResult 3 = "+DecToBin.recursion(ip));
}
}
int n = 13;
String binary = "";
//decimal to binary
while (n > 0) {
int d = n & 1;
binary = d + binary;
n = n >> 1;
}
System.out.println(binary);
//binary to decimal
int power = 1;
n = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
n = n + Character.getNumericValue(binary.charAt(i)) * power;
power = power * 2;
}
System.out.println(n);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.