Java Decimal To Binary - Big Numbers to Binary - java

My program should convert decimal numbers to binary. For big numbers it is giving me a negative number not a binary number. Why is this?
For example, if I supply 2321 I get 100100010001, which is fine. But if I supply
241242141 I get -2127232070093227171.
I can't use strings, arrays, functions. There is another option without define it as string? the output?
import java.util.Scanner;
public class d {
public static void main(String[] args) {
long num = 0;
long temp = 0L;
Scanner sc = new Scanner(System.in);
num = sc.nextLong();
long place = 1L;
long output = 0;
//System.out.print(""+ num%2+ (num%2)%2);
while(num != 0) {
temp = num % 2;
num = num / 2;
output += (place*temp);
place *=10;
}
System.out.print(""+output);
}
}

You problem is here
output += (place*temp);
place *=10;
this is producing a number which overflows.
A simple alternative is to create a String instead of generating a number you will convert to a String anyway.
StringBuilder output = new StringBuilder();
while(num != 0) {
output.append(num & 1);
num >>>= 1;
}
System.out.print(output.reverse());
or even
StringBuilder output = new StringBuilder();
for(long num = sc.netLong(); num != 0; num >>>= 1)
output.append(num & 1);
System.out.print(output.reverse());
If you want to use no functions except input or output.
long num = 241242141;
int shift = 63;
while (num >>> shift == 0 && shift > 0) shift--;
for (; shift >= 0; shift--)
System.out.print((num >>> shift) & 1);
// for comparison only
System.out.println("\n"+Long.toBinaryString(num));
prints
1110011000010001000000011101
1110011000010001000000011101

The problem is that, you are storing your Binary Equivalent in a long type, which cannot store such a long values.
You should rather use a StringBuilder and append your remainder - temp in it.
Then print it in reverse: -
StringBuilder builder = new StringBuilder();
while(num != 0) {
temp = num % 2;
num = num / 2;
builder.append(temp);
output += (place*temp);
place *=10;
}
System.out.println(builder.reverse());
If you don't need to use any methods, then just use String Concatenation, and then a loop to print the string in reverse: -
String builder = "";
while(num != 0) {
temp = num % 2;
num = num / 2;
builder += temp;
output += (place*temp);
place *=10;
}
for (int i = builder.length() - 1; i >= 0; i--) {
System.out.print(builder.charAt(i));
}
But, beware, this will create a large number of String objects on Heap. Also, here you are using a charAt method, that you have to use.

With recursion:
public class d {
static void toBinaryString( long number )
{
if( number > 1 ) toBinaryString( number / 2L );
System.out.print( number % 2L );
}
public static void main(String[] args) {
long num = 241242141L;
System.out.println( Long.toBinaryString( num ));
toBinaryString( num );
}
}
The ouput:
1110011000010001000000011101
1110011000010001000000011101

Related

Convert from decimal to binary Java error

I'm writing a simple Java program to convert from decimal to binary.
public static int toBinary(int n) {
int result = 0;
while (n >= 1) {
int power = 0;
while ((int) Math.pow(2, power) <= n) {
power++;
}
result += (int) Math.pow(10, power - 1);
n = n - (int) Math.pow(2, power - 1);
}
return result;
}
The program works for n up until 1023, but fails after that and I'm not sure where I did wrong. Can someone help?
Your code has a problem of Integer Overflow.
Binary of 1024 is 10,000,000,000 and the max value an int can hold is 2,147,483,647.
Use an int array to store the number:
public static void convertBinary(int num) {
int[] binary = new int[40];
int index = 0;
while (num > 0) {
binary[index++] = num % 2;
num /= 2;
}
for (int i = index - 1; i >= 0; i--){
System.out.print(binary[i]);
}
}
You can also use the in-built method.
System.out.println(Integer.toBinaryString(1024));
You can also use StringBuilder to store the result:
public static void convertBinary(int num){
StringBuilder binary = new StringBuilder();
while (num > 0){
binary.append(num % 2);
num = num / 2;
}
System.out.println(binary.reverse());
}
Do not use String (immutable) in a loop, always use a StringBuilder (mutable).

how can i fix this i want to convert decimal number to binary

public class Binar{
public static void main(String[] args){
int num = 7;
long Binary = cBtD(num);
System.out.printf("%d numri decimal = %d binar" , num, Binary);
}
public static long cBtD(int num){
long BinaryNumber = 0;
int i = 0;
long reminder;
while(num > 0){
reminder = num % 2;
num /= 2;
++i;
}
for (int j = i - 1; j >= 0; j--) {
System.out.print(BinaryNumber[j]);
}
return BinaryNumber;
}}
and i have this error and it says "array required, but long found" and "System.out.print(BinaryNumber[j]);"
Reason behind this error is, you have defined BinaryNumber variable as long and it is not an array. But you are trying to access it like an array. Please check my modified answer below:
public class Binar {
public static void main(String[] args) {
int num = 7;
String Binary = cBtD(num);
System.out.printf("%d numri decimal = %s binar", num, Binary);
}
public static String cBtD(int num) {
String BinaryNumber = "";
long reminder;
if (num == 0) {
return "0";
}
while (num > 0) {
reminder = num % 2;
BinaryNumber = String.valueOf(reminder).concat(BinaryNumber);
num /= 2;
}
return BinaryNumber;
}
}
That error occurred because you defined BinaryNumber's type 'long' and you wanted use it as an array.
I change it a bit, try it:
public class Binar {
public static void main(String[] args) {
int num = 7;
int[] binaryArray = cBtD(num);
String numbers = "";
for (int aBinaryArray : binaryArray)
numbers += aBinaryArray;
System.out.printf("%d numri decimal = %d binar" , num, Integer.parseInt(numbers));
}
private static int[] cBtD(int num){
int i = 0;
int temp[] = new int[7];
int binaryNumber[];
while (num > 0) {
temp[i++] = num % 2;
num /= 2;
}
binaryNumber = new int[i];
int k = 0;
for (int j = i - 1; j >= 0; j--) {
binaryNumber[k++] = temp[j];
}
return binaryNumber;
}
}
Or you can simply use these methods to convert decimal to binary:
Integer.toBinaryString();
Or this:
Integer.toString(n,2);
All numbers are inherently binary. But whether you display them in binary or hex or octal is simply a matter of representation. Which means you want to print them as a string. Even when you do the following:
int v = 123;
System.out.println(v); // v is printed as a decimal string.
So to convert them to a binary string, just prepend the remainders to the string after dividing by two (via the remainder operator).
int n = 11;
String s = "";
s = (n%2) + s; // s = "1"
n/=2; // n == 5
s = (n%2) + s; // s = "11"
n/=2 // n == 2
s = (n%2) + s; // s = "011";
n/=2 // n == 1
s = (n%2) + s; // s = "1011";
n/=2; // n == 0
n == 0 so your done.
return s and print it.

Adding numbers which are stored in string variables

Given two non-negative numbers num1 and num2 represented as strings, return the sum of num1 and num2.
The length of both num1 and num2 is less than 5100.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zeros.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
I tried my solution but it doesn't work. Suggestions?
public class Solution {
public String addStrings(String num1, String num2) {
double multiplier = Math.pow(10, num1.length() - 1);
int sum = 0;
for (int i = 0; i < num1.length(); i++){
sum += ((((int) num1.charAt(i)) - 48) * multiplier);
multiplier /= 10;
}
multiplier = Math.pow(10, num2.length() - 1);
for (int i = 0; i < num2.length(); i++){
sum += ((((int) num2.charAt(i)) - 48) * multiplier);
multiplier /= 10;
}
return "" + sum;
}
}
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Note that you are adding two integers of up to 5100 digits each. That is not that max value, but the max number of digits.
An int (your sum variable) cannot hold values like that. BigInteger can, but you're not allowed to use it.
So, add the numbers like you would on paper: Add last digits, write lower digit of the sum as last digit of result, and carry-over a one if needed. Repeat for second-last digit, third-last digit, etc. until done.
Since the sum will be at least the number of digits of the longest input value, and may be one longer, you should allocate a char[] of length of longest input plus one. When done, construct final string using String(char[] value, int offset, int count), with an offset of 0 or 1 as needed.
The purpose of this question is to add the numbers in the string form. You should not try to convert the strings to integers. The description says the length of the numbers could be up to 5100 digits. So the numbers are simply too big to be stored in integers and doubles. For instance In the following line:
double multiplier = Math.pow(10, num1.length() - 1);
You are trying to store 10^5100 in a double. In IEEE 754 binary floating point standard a double can a store number from ±4.94065645841246544e-324 to ±1.79769313486231570e+308. So your number won't fit. It will instead turn into Infinity. Even if it fits in double it won't be exact and you will encounter some errors in your follow up calculations.
Because the question specifies not to use BigInteger or similar libraries you should try and implement string addition yourself.
This is pretty straightforward just implement the exact algorithm you follow when you add two numbers on paper.
Here is working example of adding two strings without using BigInteger using char array as intermediate container. The point why double can't be used has been explained on #Tempux answer. Here the logic is similar to how adding two numbers on paper works.
public String addStrings(String num1, String num2) {
int carry = 0;
int m = num1.length(), n = num2.length();
int len = m < n ? n : m;
char[] res = new char[len + 1]; // length is maxLen + 1 incase of carry in adding most significant digits
for(int i = 0; i <= len ; i++) {
int a = i < m ? (num1.charAt(m - i - 1) - '0') : 0;
int b = i < n ? (num2.charAt(n - i - 1) - '0') : 0;
res[len - i] = (char)((a + b + carry) % 10 + '0');
carry = (a + b + carry) / 10;
}
return res[0] == '0' ? new String(res, 1, len) : new String(res, 0, len + 1);
}
This snippet is relatively small and precise because here I didn't play with immutable String which is complicated/messy and yield larger code. Also one intuition is - there is no way of getting larger output than max(num1_length, num2_length) + 1 which makes the implementation simple.
You have to addition as you do on paper
you can't use BigInteger and the String Length is 5100, so you can not use int or long for addition.
You have to use simple addition as we do on paper.
class AddString
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 = "98799932345";
String s2 = "99998783456";
//long n1 = Long.parseLong(s1);
//long n2 = Long.parseLong(s2);
System.out.println(addStrings(s1,s2));
//System.out.println(n1+n2);
}
public static String addStrings(String num1, String num2) {
StringBuilder ans = new StringBuilder("");
int n = num1.length();
int m = num2.length();
int carry = 0,sum;
int i, j;
for(i = n-1,j=m-1; i>=0&&j>=0;i--,j--){
int a = Integer.parseInt(""+num1.charAt(i));
int b = Integer.parseInt(""+num2.charAt(j));
//System.out.println(a+" "+b);
sum = carry + a + b;
ans.append(""+(sum%10));
carry = sum/10;
}
if(i>=0){
for(;i>=0;i--){
int a = Integer.parseInt(""+num1.charAt(i));
sum = carry + a;
ans.append(""+(sum%10));
carry = sum/10;
}
}
if(j>=0){
for(;j>=0;j--){
int a = Integer.parseInt(""+num2.charAt(j));
sum = carry + a;
ans.append(""+(sum%10));
carry = sum/10;
}
}
if(carry!=0)ans.append(""+carry);
return ans.reverse().toString();
}
}
You can run the above code and see it works in all cases, this could be written in more compact way, but that would have been difficult to understand for you.
Hope it helps!
you can use this one that is independent of Integer or BigInteger methods
public String addStrings(String num1, String num2) {
int l1 = num1.length();
int l2 = num2.length();
if(l1==0){
return num2;
}
if(l2==0){
return num1;
}
StringBuffer sb = new StringBuffer();
int minLen = Math.min(l1, l2);
int carry = 0;
for(int i=0;i<minLen;i++){
int ind = l1-i-1;
int c1 = num1.charAt(ind)-48;
ind = l2-i-1;
int c2 = num2.charAt(ind)-48;
int add = c1+c2+carry;
carry = add/10;
add = add%10;
sb.append(add);
}
String longer = null;
if(l1<l2){
longer = num2;
}
else if(l1>l2){
longer = num1;
}
if(longer!=null){
int l = longer.length();
for(int i=minLen;i<l;i++){
int c1 = longer.charAt(l-i-1)-48;
int add = c1+carry;
carry = add/10;
add = add%10;
sb.append(add);
}
}
return sb.reverse().toString();
}
The method takes two string inputs representing non-negative integers and returns the sum of the integers as a string. The algorithm works by iterating through the digits of the input strings from right to left, adding each digit and any carryover from the previous addition, and appending the resulting sum to a StringBuilder. Once both input strings have been fully processed, any remaining carryover is appended to the output string. Finally, the string is reversed to produce the correct output order.
Hope this will solve the issue.!
public string AddStrings(string num1, string num2)
{
int i = num1.Length - 1, j = num2.Length - 1, carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0 || carry != 0) {
int x = i >= 0 ? num1[i--] - '0' : 0;
int y = j >= 0 ? num2[j--] - '0' : 0;
int sum = x + y + carry;
sb.Append(sum % 10);
carry = sum / 10;
}
char[] chars = sb.ToString().ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
Previous solutions have excess code. This is all you need.
class ShortStringSolution {
static String add(String num1Str, String num2Str) {
return Long.toString(convert(num1Str) + convert(num2Str));
}
static long convert(String numStr) {
long num = 0;
for(int i = 0; i < numStr.length(); i++) {
num = num * 10 + (numStr.charAt(i) - '0');
}
return num;
}
}
class LongStringSolution {
static String add(String numStr1, String numStr2) {
StringBuilder result = new StringBuilder();
int i = numStr1.length() - 1, j = numStr2.length() - 1, carry = 0;
while(i >= 0 || j >= 0) {
if(i >= 0) {
carry += numStr1.charAt(i--) - '0';
}
if(j >= 0) {
carry += numStr2.charAt(j--) - '0';
}
if(carry > 9) {
result.append(carry - 10);
carry = 1;
} else {
result.append(carry);
carry = 0;
}
}
if(carry > 0) {
result.append(carry);
}
return result.reverse().toString();
}
}
public class Solution {
static String add(String numStr1, String numStr2) {
if(numStr1.length() < 19 && numStr2.length() < 19) {
return ShortStringSolution.add(numStr1, numStr2);
}
return LongStringSolution.add(numStr1, numStr2);
}
}
For the sake of comprehension of the question
your method's name is addition
you are trying to do a power operation but the result is stored in a variable named multiplication...
there is more than one reason why that code doesnt work...
You need to do something like
Integer.parseInt(string)
in order to parse strings to integers
here the oficial doc

decimal to binary output is incorrect

I can only get correct output for decimal less than five. the output for five is 110 when it should be 101. the output for six is 101 and the output for ten is 1100.
//while loop divides each digit
while (decimal > 0)
{
//divides and digit becomes the remainder
int digit = decimal % 2;
//makes the digit into a string builder so it can be reversed
binaryresult.append(digit);
decimal = decimal / 2;
display.setText(binaryresult.reverse());
}
Usee the below code it may work for you
import java.util.Scanner;
public class decToBinary{
public String decToBin(int n) {
StringBuilder result = new StringBuilder();
int i = 0;
int b[] = new int[10];
while (n != 0) {
i++;
b[i] = n % 2;
n = n / 2;
}
for (int j = i; j > 0; j--) {
result.append(b[j]);
}
return result.toString();
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter decimal no :");
int n=sc.nextInt();
System.out.println("binary numbers is :");
decToBinary dtb = new decToBinary();
System.out.println(dtb.decToBin(n));
}
}
Something like this may be closer to what you are asking for:
while (decimal > 0) {
result.insert(0, (char) ((decimal % 2) + '0'));
decimal /= 2;
}
It uses insert to avoid reversing and adds the character instead of the number.
But you would be better off using a built in mechanism such as:
BigInteger.valueOf(decimal).toString(2)
i am not able to reproduce the behaviour using the following:
public static String decToBin(int n) {
StringBuilder result = new StringBuilder();
while (n > 0) {
int dec = n % 2;
result.append(dec);
n = n / 2;
}
return result.reverse().toString();
}
however, consider using the build-in
public static String decToBin(int n) {
return Integer.toBinaryString(n);
}
(or even BigInteger as stated above)
try this code , i hope this is what u r looking for:
public class DecimalToBinary {
public static void main(String[] args)
{
int decimal=11;
StringBuffer binaryValue=new StringBuffer();
while(decimal>0 ){
int rem=decimal%2;
decimal=decimal/2;
System.out.println("Remainder:"+rem);
binaryValue.append(rem);
}
System.out.println("binary is:"+binaryValue.reverse());
}
}

Decimal to binary homework in Java

I have a homework to do a decimal to binary conversation. This is the code I have:
int num = 0;
int temp = 0;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
//System.out.print(""+ num%2+ (num%2)%2);
while(num != 0) {
temp = num;
System.out.print(""+(int) temp % 2);
num = num / 2;
}
It is working fine, but it giving me the output as LSB and not as MSB.
For example:
35
110001
but I need it to be 100011.
I cannot use any function or method to reverse it. I know I can put it in an array, string or whatever and do some magic. But I can use only the while loop, modulo and print.
Any Suggestions?
Instead of starting at the bottom bit, you can start at the top bit.
int i = 35;
// find where the top bit is.
int shift = 0;
while (i >>> (shift + 1) > 0) shift++;
// print from the top bit down
while (shift >= 0)
System.out.print((i >>> shift--) & 1);
prints i = 35
100011
prints for i = -35
11111111111111111111111111011101
Numbers are really right-to-left (guess why they call it 'Arabic numerals'?). The least significant digit of a number is its last digit.
You generate binary digits from least significant to most significant. You have to store them and then print in reverse order, from most significant to least significant.
Try using a List<Integer> or an int[] for this.
Don't output each digit as you find them. Build your output incrementally and then print it at the end.
public static void main(String[] args)
{
int num = 0;
int temp = 0;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
int place = 1;
int output = 0;
while(num != 0) {
temp = num % 2;
num = num / 2;
output += (place*temp);
place *=10;
}
System.out.print(""+output);
}
You may need to modify this to handle large or negative numbers.
One work around could be as below:
int indx = 0;
if(num<0){
indx =31;
num = Integer.MAX_VALUE+num+2;
}else{
while((int)Math.pow(2, indx) <= num){
indx++;
}
indx--;//get the highest index
}
System.out.print(""+1);//print the highest bit
num = num % (int)Math.pow(2, indx);
indx--;
//print the bits right to left
for(int i = indx; i >=0; i--){
if(Math.abs(num)<2){
System.out.print(""+num);
}else if((int)Math.pow(2, i) >= num){
System.out.print(""+0);
}else{
num = num % (int)Math.pow(2, i); //get the remaining value
System.out.print(""+1);
}
}

Categories

Resources