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);
}
}
Related
I've been trying to sum a certain digit from a number, for example
Number: 5
Input: 54365
Output: The sum of 5's is 10
Second example:
Number: 5
Input: 5437555
Output: The sum of 5's is 20
I've managed to separate the digits yet I couldn't find the condition to sum
a certain number (for instance number 5 like the examples).
I'd appreciate to hear your idea of doing it
public static void main(String[] args) {
int sum = 0;
int number = MyConsole.readInt("Enter a number:");
while (number > 0) {
if (number % 10 == 8) {
sum += 8;
} else {
number /= 10;
}
}
System.out.println("The sum of 8's is:" + sum);
}
My way of separating the numbers.
Also i have a small program to get input instead of using scanner since we still haven't went through it in class.
Your requirement seems reasonably clear to me.
Given a number
final int number = 5;
And a starting number
final int input = 54365;
The easiest way is to convert that number to a String
final int inputStr = String.valueOf(input);
Then, you can filter each char for it, and sum them
final int sum =
inputStr.chars() // Get a Stream of ints, which represent the characters
.map(Character::getNumericValue) // Convert a char to its numeric representation
.filter(i -> i == number) // Filter for the designated number
.sum(); // Sum all the filtered integers
Output: 10
Using the same approach, but with an old-style for loop
final int input = 54365;
final int inputStr = String.valueOf(input);
final int number = 5;
int sum = 0;
for (final char c : inputStr.toCharArray()) {
final int n = Character.getNumericValue(c);
if (n == number) {
sum += number;
}
}
Your solution can work
int number = 5;
int input = 543655;
int sum = 0;
while (input > 0) {
if (input % 10 == number) {
sum += number;
}
input /= 10;
}
excepted output : 1/4,1/2,3/4,1,5/4,3/2
but my output is coming as in the decimal form . Please help how to print in the form of fraction only.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(sum+" ");
}
}}
take input in form of string so it will take input in required format and split it by "/" i.e someString.spit("/").
after that make one for loop and take two number and in two different variable store it.
and then take division for both and print it by using "/" in between them.
public class NewClass {
public static void main(String[] args) {
System.out.println(convertype(0.75));
}
public static String convertype(double decimal){
int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint))); // 10^2 is your denominator
int gcd = numerator.gcd(denominator).intValue(); // calculate the greatest common divisor of numerator and denominator
if (gcd > 1 ){ // gcd(75,100) = 25
return String.valueOf(numerator.intValue()/gcd) +" / " + String.valueOf(denominator.intValue()/gcd); // return 75/25 / 100/25 = 3/4
}
else{
return String.valueOf(numerator) +" / " + String.valueOf(denominator); // if gcd = 1 which means nothing to simplify just return numerator / denominator
}
}
}
Wrote a method where you can convert double numbers to fraction. Use this to convert it and print as below,
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(toFraction(sum)+" ");
}
}
static String toFraction(double x) {
int w = (int) x;
int n = (int) (x * 64) % 64;
int a = n & -n;
return n == 0 ? w+"" : (w * (64 / a) + (n / a)) + "/" + 64 / a;
}
}
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));
}
}
}
I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.
My first attempt:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
int tempRev = RevDigs(input/10);
if(tempRev >= 10)
reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;
if(tempRev <10 && tempRev >0)
reverse = input%10*10 + tempRev;
if(tempRev == 0)
reverse = input%10;
return reverse;
}//======================
I also tried to use this, but it seems to mess up middle digits:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
if(RevDigs(input/10) == 0)
reverse = input % 10;
else
{
if(RevDigs(input/10) < 10)
reverse = (input % 10) *10 + RevDigs(input/10);
else
reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);
}
return reverse;
}
I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.
How about using two methods
public static long reverse(long n) {
return reverse(n, 0);
}
private static long reverse(long n, long m) {
return n == 0 ? m : reverse(n / 10, m * 10 + n % 10);
}
public static void main(String... ignored) {
System.out.println(reverse(123456789));
}
prints
987654321
What about:
public int RevDigs(int input) {
if(input < 10) {
return input;
}
else {
return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
/* here we:
- take last digit of input
- multiply by an adequate power of ten
(to set this digit in a "right place" of result)
- add input without last digit, reversed
*/
}
}
This assumes input >= 0, of course.
The key to using recursion is to notice that the problem you're trying to solve contains a smaller instance of the same problem. Here, if you're trying to reverse the number 13579, you might notice that you can make it a smaller problem by reversing 3579 (the same problem but smaller), multiplying the result by 10, and adding 1 (the digit you took off). Or you could reverse the number 1357 (recursively), giving 7531, then add 9 * (some power of 10) to the result. The first tricky thing is that you have to know when to stop (when you have a 1-digit number). The second thing is that for this problem, you'll have to figure out how many digits the number is so that you can get the power of 10 right. You could use Math.log10, or you could use a loop where you start with 1 and multiply by 10 until it's greater than your number.
package Test;
public class Recursive {
int i=1;
int multiple=10;
int reqnum=0;
public int recur(int no){
int reminder, revno;
if (no/10==0) {reqnum=no;
System.out.println(" reqnum "+reqnum);
return reqnum;}
reminder=no%10;
//multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
i++;
no=recur(no/10);
reqnum=reqnum+(reminder*multiple);
multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
return reqnum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=123456789;
Recursive r= new Recursive();
System.out.println(r.recur(num));
}
}
Try this:
import java.io.*;
public class ReversalOfNumber {
public static int sum =0;
public static void main(String args []) throws IOException
{
System.out.println("Enter a number to get Reverse & Press Enter Button");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
int number = Integer.parseInt(input);
int revNumber = reverse(number);
System.out.println("Reverse of "+number+" is: "+revNumber);
}
public static int reverse(int n)
{
int unit;
if (n>0)
{
unit = n % 10;
sum= (sum*10)+unit;
n=n/10;
reverse(n);
}
return sum;
}
}
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;
}
}