Binary to Decimal Conversion Java Code Bug - java

So I'm doing a project where I have to do conversions from binary numbers to decimals etc.
This is my code so far and there is a bug. In a binary number such as 1101 the decimal number that is suppose to come out is 13 but the number that comes out of the code is 11. This bug happens to all binary numbers that starts with a bunch of 1's and like a single 0.
import java.util.*; // imports everything in java.util
public class newCalculator{
* Conversion asks the user for a binary number. It converts the input to a decimal number
* using arrays and then displays the answer to the screen.
*/
public static void main (String[]args){ // creates the main method
binaryToDecimal(); //calls the user defined method binaryToDecimal
}
public static void binaryToDecimal() {
Scanner scan = new Scanner(System.in); // Creates a new Scanner
System.out.println("Input a Binary Number"); // Asks the user to input their number
String binary = scan.next(); // Creates a new String that stores the value of the input
char[] charArray = binary.toCharArray(); //Create a new Array and implements in the input
double answer = 0; // Creates a new double called answer setting it to zero
for (double index = 0; index < charArray.length; index++){//For loop
if (charArray[(int)index] == '1') {//If statement that allows the binary input to work
answer = answer + Math.pow(2.0, index);//Sets the answer with the math class power of 2
}
}
System.out.println(answer);//Prints out the final conversion result
/* Test Cases Expected Result Output
* 101 5 5
* 11 3 3
* 1 1 1
* 1101 13 11<--
* 111 7 7
* 1000001 65 65
* 1111 15 15
* 1001 9 9
* 11101 29 23<--
* 10101 21 21
*
*/
}
}

Your expected results are being calculated as if the binary string is read from right to left; however, your code is reading the binary string from left to right.
Change this:
for (double index = 0; index < charArray.length; index++){
To this:
for (double index = charArray.length - 1; index >= 0; index--) {
You should also change to using an integer as your index, like this:
for (int index = charArray.length - 1; index >= 0; index--) {

You are going through your bits in the wrong order. Your first index refers to the most significant bit, not the least significant bit.
Your call to Math.pow should be
answer = answer + Math.pow(2.0, (charArray.length - index - 1));
And as Tom Leese has already pointed out, please use an integer for your looping index.

Symmetry is the answer. If you look into all your tests inputs they all are symmetrical except 1101
Your algorithm is correct with the exception that instead of index in Math.pow you need to use Math.pow(2.0, charArray.length - i - 1), below is the correct implementation(really only small incremental change)
import java.util.Scanner;
public class NewCalc {
public static void main(String[] args) {
binaryToDecimal();
}
public static void binaryToDecimal() {
Scanner scan = new Scanner(System.in);
System.out.println("Input a Binary Number");
String binary = scan.next();
char[] charArray = binary.toCharArray();
double answer = 0;
for (int i = 0; i < charArray.length; i++) {
answer = charArray[i] == '1'
? answer + Math.pow(2.0, charArray.length - i - 1)
: answer;
}
System.out.println(answer);
}
}

package pdaproject;
import java.util.Scanner;
public class NewCalc {
public static void main(String[] args) {
binaryToDecimal();
}
// convert to decimal (base 10)
public static void binaryToDecimal() {
Scanner scan = new Scanner(System.in);
System.out.println("Input a Binary Number");
String binary = scan.next();
int answer = 0;
// process left to right
for (int i = 0; i < binary.length(); i++) {
answer = 2 * answer + (binary.charAt(i) == '1' ? 1 : 0);
}
System.out.println(answer);
}
}

public class BinaryToDecimal {
static int testcase1=1001;
public static void main(String[] args) {
BinaryToDecimal test = new BinaryToDecimal();
int result = test.convertBinaryToDecimal(testcase1);
System.out.println(result);
}
//write your code here
public int convertBinaryToDecimal(int binary)
{
int deci = 0;
int p=1;
int rem = 0;
while(binary>0)
{
rem = binary%10;
deci = deci+(rem*p);
p = p*2;
binary = binary/10;
}
return deci;
}
}

Related

How to put numbers to array in while loop in java?

I am trying to add two binary numbers and then get their sum in binary system. I got their sum in decimal and now I am trying to turn it into binary. But there is problem that when I take their sum (in decimal) and divide by 2 and find remainders(in while loop), I need to put remainders into array in order print its reverse. However, there is an error in array part. Do you have any suggestions with my code? Thanks in advance.
Here is my code:
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int k = dec1(n)+dec2(m);
int i=0,c;
int[] arr= {};
while(k>0) {
c = k % 2;
k = k / 2;
arr[i++]=c; //The problem is here. It shows some //error
}
while (i >= 0) {
System.out.print(arr[i--]);
}
}
public static int dec1(int n) {
int a,i=0;
int dec1 = 0;
while(n>0) {
a=n%10;
n=n/10;
dec1= dec1 + (int) (a * Math.pow(2, i));
i++;
}
return dec1;
}
public static int dec2(int m) {
int b,j=0;
int dec2 = 0;
while(m>0) {
b=m%10;
m=m/10;
dec2= dec2 + (int) (b * Math.pow(2, j));
j++;
}
return dec2;
}
}
Here:
int[] arr= {};
creates an empty array. Arrays don't grow dynamically in Java. So any attempt to access any index of arr will result in an ArrayIndexOutOfBounds exception. Because empty arrays have no "index in bounds" at all.
So:
first ask the user for the count of numbers he wants to enter
then go like: int[] arr = new int[targetCountProvidedByUser];
The "more" real answer would be to use List<Integer> numbersFromUsers = new ArrayList<>(); as such Collection classes allow for dynamic adding/removing of elements. But for a Java newbie, you better learn how to deal with arrays first.
Why are you using two different methods to do the same conversion? All you need is one.
You could have done this in the main method.
int k = dec1(n)+dec1(m);
Instead of using Math.pow which returns a double and needs to be cast, another alternative is the following:
int dec = 0;
int mult = 1;
int bin = 10110110; // 128 + 48 + 6 = 182.
while (bin > 0) {
// get the right most bit
int bit = (bin % 10);
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// Sum up each product, multiplied by a running power of 2.
// this is required since bits are taken from the right.
dec = dec + mult * bit;
bin /= 10;
mult *= 2; // next power of 2
}
System.out.println(dec); // prints 182
An alternative to that is to use a String to represent the binary number and take the bits from the left (high order position).
String bin1 = "10110110";
int dec1 = 0;
// Iterate over the characters, left to right (high to low)
for (char b : bin1.toCharArray()) {
// convert to a integer by subtracting off character '0'.
int bit = b - '0';
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// going left to right, first multiply by 2 and then add the bit
// Each time thru, the sum will be multiplied by 2 which shifts everything left
// one bit.
dec1 = dec1 * 2 + bit;
}
System.out.println(dec1); // prints 182
One possible way to display the result in binary is to use a StringBuilder and simply insert the converted bits to characters.
public static String toBin(int dec) {
StringBuilder sb = new StringBuilder();
while (dec > 0) {
// by inserting at 0, the bits end up in
// correct order. Adding '0' to the low order
// bit of dec converts to a character.
sb.insert(0, (char) ((dec & 1) + '0'));
// shift right for next bit to convert.
dec >>= 1;
}
return sb.toString();
}

why does the c value gets repeated in the given code?

1.This is my code to convert binary to decimal but its not working.The c value gets repeated for some reasons.
/**
* Created by Ranjan Yadav on 11.10.2016.
*/
public class BinaryToDecimal {
public static void main(String[] args) {
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
int binary = read.nextInt();
int total = 0;
int n = 1;
int c = 0;
int number = 0;
while (binary != 0) {
c = binary % ((int) Math.pow(10, n));
binary = binary / 10;
number = c * (int)(Math.pow(2, (n - 1)));
total += number;
++n;
}
System.out.printf("The decimal of the binary is %d", total);
}
}
You were increasing n by 1 and dividing binary by 10 raised to n at same time. Due to this, you were not able to fetch the unit's digit of binary number after 1st iteration. To solve this issue, you need to get binary modulo 10 (not 10 raised to n) in each iteration and also keep the statement of binary divided by 10.
I have simplified and also made some small changes to your code to increase readability. Here is the corrected main method :
public static void main (String[] args){
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
int binary = read.nextInt();
int total = 0;
int n = 0;
int c = 0;
int number = 0;
while (binary != 0) {
c = binary % 10;
binary = binary / 10;
number = c * (int)(Math.pow(2, n));
total += number;
++n;
}
System.out.println("The decimal of the binary is " + total);
}
The code is working and producing desired results. Let me know in case you have any further doubts.
You can just parse the integer with the parseInt method:
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = read.nextLine();
int decimal = Integer.parseInt(binary, 2); // 2 here means the string "binary" is in binary
If you're not allowed to use that, try this algorithm:
Create a variable total and make it 0.
Loop through the binary string with a for loop like this: for (int i = 0 ; i < binaryString.length() ; i++)
In each iteration, if the character is 1, add Math.pow(2, binaryString.length() - 1 - i). Otherwise do nothing.

Converting decimal to binary (Java)

I'm trying to convert decimal to binary but some how when I convert 128 binary the output gives me 11111110, I tried to fix the calculation but still end up with the same output.
import java.lang.*;
public class HA7BinaryErr {
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
int number = 0;
int factorOfTwo = 0;
// get number to convert from user
do {
System.out.println("Enter the number to convert (0-255): ");
number = input.nextInt();
} while (number < 0 || number > 255);
System.out.println("The number " + number + " converted to binary is : ");
// convert to binary by successively dividing by larger factors of 2
for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo *= 2) {
if (number / factorOfTwo >= 1) {
System.out.print("1");
number -= factorOfTwo;
} else
System.out.print("0");
}
} // end of main
}// end of class
You have a problem that you are writing the number backwards. You need to start with the highest bit first
for (int powerOfTwo = 128; powerOfTwo > 0; powerOfTwo /= 2) {
When you are writing in decimal you start with the highest power e.g. 1234 is 1 * 1000 + 2 * 100 + 3 * 10 + 4 * 1
You could take the easy way out and use:
Integer.toBinaryString(int i) then print the string to the console.
Check it out here.
public class DCTB {
public void convertor(int n)
{
for(int i=0;i<10;i++)
{
int arr=(int) (n%2);
n=n/2;
System.out.println(Integer.toString(arr));
}
}
public static void main(String args[])
{
DCTB obj=new DCTB();
obj.convertor(10);
}
}

Binary to decimal in java using only recursion (no loops)

I can not seem to get my method to convert the binary number to a decimal correctly. I believe i am really close and in fact i want to use a string to hold the binary number to hold it and then re-write my method to just use a .length to get the size but i do not know how to actually do that. Could someone help me figure out how i'd rewrite the code using a string to hold the binary value and then obtain the decimal value using only recursion and no loops?
This is my full code right now and i won't get get rid of asking for the size of the binary and use a string to figure it out myself. Please help :)
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer and size : ");
input = scan.nextInt();
size = scan.nextInt();
System.out.println(binaryToDecimal(input, size));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
}
public static int binaryToDecimal(int binary, int size) {
if (binary == 0) {
return 0;
}
return binary % 10
* (int) Math.pow(2, size) + binaryToDecimal((int) binary / 10, size - 1);
}
}
Here is an improved version
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer : ");
int input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
String binInput = scan.next();
System.out.println(binaryToDecimal(binInput));
}
public static void convert(int num) {
if (num>0) {
convert(num/2);
System.out.print(num%2 + " ");
}
}
public static int binaryToDecimal(String binInput){
int len = binInput.length();
if (len == 0) return 0;
String now = binInput.substring(0,1);
String later = binInput.substring(1);
return Integer.parseInt(now) * (int)Math.pow(2, len-1) + binaryToDecimal(later);
}
}
Don't parse binary in reverse order.
Here by calling binaryToDecimal(int) it will return decimal number.
public static int binaryToDecimal(int binary) {
return binaryToDecimal(binary, 0);
}
public static int binaryToDecimal(int binary, int k) {
if (binary == 0) {
return 0;
}
return (int) (binary % 10 * Math.pow(2, k) + binaryToDecimal(binary / 10, k + 1));
}
If you are coding just to convert numbers (not for practice). Then better approach would be to use Integer.parseInt(String, 2). Here you will have to pass binary number in the form of String.
If you are looking to do this using a String to hold the binary representation, you could use the following:
public static int binaryToDecimal(String binaryString) {
int size = binaryString.length();
if (size == 1) {
return Integer.parseInt(binaryString);
} else {
return binaryToDecimal(binaryString.substring(1, size)) + Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1);
}
}
How this works, is with the following logic. If, the number you send it is just 1 character long, or you get to the end of your recursive work, you will return just that number. So for example, 1 in binary is 1 in decimal, so it would return 1. That is what
if (size == 1) {
return Integer.parseInt(binaryString);
}
Does. The second (and more important part) can be broken up into 2 sections. binaryString.substring(1, size) and Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1). The call made in the return statement to
binaryString.substring(1, size)
Is made to pass all but the first number of the binary number back into the function for calculation. So for example, if you had 11001, on the first loop it would chop the first 1 off and call the function again with 1001. The second part, is adding to the total value whatever the value is of the position number at the head of the binary representation.
Integer.parseInt(binaryString.substring(0, 1))
Gets the first number in the current string, and
* (int) Math.pow(2, size - 1)
is saying Multiple that by 2 to the power of x, where x is the position that the number is in. So again with our example of 11001, the first number 1 is in position 4 in the binary representation, so it is adding 1 * 2^4 to the running total.
If you need a method to test this, I verified it working with a simple main method:
public static void main(String args[]) {
String binValue = "11001";
System.out.println(binaryToDecimal(binValue));
}
Hopefully this makes sense to you. Feel free to ask questions if you need more help.
Here is the clean and concise recursive algorithm; however, you'll need to keep track of some global variable for power, and I have defined it as a static member.
static int pow = 0;
public static int binaryToDecimal(int binary) {
if (binary <= 1) {
int tmp = pow;
pow = 0;
return binary * (int) Math.pow(2, tmp);
} else {
return ((binary % 10) * (int) Math.pow(2, pow++)) + binaryToDecimal(binary / 10);
}
}
Note: the reason, why I introduce pow, is that static field needs to be reset.
Just did the necessary changes in your code.
In this way, you would not require the size input from the user.
And,both the conversions of decimal to binary and binary to decimal would be succesfully done.
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
input = scan.nextInt();
System.out.println(binaryToDecimal(input));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
return -1;
}
public static int binaryToDecimal(int binary) {
if(binary==0)
{
return 0;
}
else
{
String n=Integer.toString(binary);
int size=(n.length())-1;
int k=(binary%10)*(int)(Math.pow(2,size));
return k + binaryToDecimal(((int)binary/10));
}
}
}

Reversing an integer in Java using a for loop

This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}

Categories