Is there a way to convert an int to binary number without using Integer.toBinaryString method?
I tried to figure out the algorithm for the conversion but haven't had any luck with it.
My task is this: (https://open.kattis.com/problems/reversebinary)
Insert an Int with help of Scanner.
Convert the Int to binary.
Reverse the binary.
Print out the new Int.
For example, the number 11 is 1011 in binary.
Now reverse the binary number 1011 and you get 1101 (which is the number 13)
and print out 13.
This is what I got, but still, I used the Integer.toBinaryString method and I get NumberFormatException.
int reverse = 0;
int number, binary;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
String b = Integer.toString(number, 2);
binary = Integer.parseInt(b);
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
int newNumber = Integer.parseInt(String.valueOf(reverse), 2);
System.out.println(newNumber);
}
}
First of all, you should use the correct terms. You are not converting an int to a binary. The int type (as well as all numeric types) are already stored in a binary format. When you convert an int to a String, or a String to an int, you choose the radix that the String representation uses (such as decimal, binary, octal, hexadecimal, etc..). This determines the digits that appear in the String representation. Now, based on your example, what you wish to do is generate a number whose binary representation is the reverse of the input number. In other words, you want to reverse the bits of the input number.
Your current loop :
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
calculates the decimal (radix 10) digits of binary and creates an integer whose value is the value of those digits when they are arranged in reversed order.
If you want the reverse of the binary representation of the input number, you should multiply and divide by 2 in order to obtain the binary digits (aka bits) of the input number and reverse them :
while (number != 0) {
System.out.print (number % 2); // prints a binary digit (i.e. 0 or 1)
reverse = reverse * 2 + number % 2;
number = number / 2;
}
System.out.println();
System.out.println(reverse); // prints the decimal representation of the reversed number
If number is 11, reverse will be 13, since the reverse of 1011 is 1101. This code will print both the binary representation of the reversed number (1101) and the decimal representation (13).
Instead of reversing the binary as a number, reverse it while it is still a String, new StringBuilder(b).reverse().toString(). Then convert it back to an int from base 2, and you're done.
So the entire code would be:
final Scanner scn = new Scanner(System.in);
final int number = scn.nextInt();
String b = Integer.toString(number, 2);
b = new StringBuilder(b).reverse().toString();
System.out.println(Integer.parseInt(b.toString(), 2));
Maybee the smartest solution for this problem is bit shifting. I wrote an example with a little explanation.
int number, reverse = 0;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
while (number > 0)
{
// shift all bits to the left
reverse = reverse << 1;
// extract the last bit of the number
int bit = number & 1;
// add the last bit to the reverse version
reverse |= bit;
// shift alle bits to the right
number = number >> 1;
}
System.out.println(reverse);
Integer.toBinaryString - Returns a string representation of the integer argument as an unsigned integer in base 2.
String toString(int i, int radix) -
Returns a string representation of the first argument in the radix specified by the second argument
public static void main(String[] args) {
int reverse = 0;
int number, binary;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
String b = Integer.toBinaryString(number);
binary = Integer.parseInt(b);
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
int newNumber = Integer.parseInt(String.valueOf(reverse), 2);
System.out.println(newNumber);
}
Infact whatever you use cannot give an error. The above code perfectly compiles without an error.
Providing 11, gives 13 perfectly.
Related
I have upload this code already but it was having some problems and now I have update my code this program does not provide me exact reverse number when I enter 123 it return me 321 but if I enter 001 or 100 it just return me 1 in both case help me to solve this issue
public class Employee {
void fun(int choice) {
int number = choice;
int remander = 0;
int reverse = 0;
while (number >= 1) {
remander = number % 10;> taking remainder here
reverse = reverse * 10 + remander;
number = number / 10;
}
System.out.println(reverse);
}
public static void main(String args[]) {
Employee ob=new Employee();
int choice;
System.out.println("Enter number you want to return");
Scanner obj=new Scanner(System.in);
choice= obj.nextInt();
ob.fun(choice);
}
}
`
Here's a one-liner you can use to convert int to Stream of String numbers, reverse it and return as a String:
Stream.of(Integer.toString(choice).split("")).reduce((c1,c2)->c2+c1).get();
First point: be careful about adding leading 0s to the number. If the number is an integer literal, the leading 0s will actually cause the integer to be interpreted as octal. In this case, 001 octal does, in fact, equal 1 in decimal too, but only due to luck. If you picked another number, it would not give you the result you're expecting; for example, the following code actually prints 63 (not 77):
public class HelloWorld{
public static void main(String []args){
int x = 0077;
System.out.println(x);
}
}
On the other hand, if you're parsing an integer out of a string or using a scanner, the leading 0s will simply be stripped off. For example, the following prints 77:
System.out.println(Integer.parseInt("0077"));
Unfortunately, in neither case will you get 0077, so the leading 0s won't make any difference when you go to do the reverse operation.
Also, think about what happens for 100:
reverse = reverse * 10 + remander;
Reverse is 0 to start with (and 0 * 10 == 0) and 100 % 10 == 0 because 100 is evenly divisible by 10. Put another way, the statement is equal to:
reverse = 0 * 10 + 0;
which clearly equals 0.
You can't do this using Scanner.nextInt() because there is no way to tell if leading zeroes were included once they are converted to an int. And the octal situation is not relevant since Scanner does not process ints that way. So you use either an all String solution and verify the characters are digits or use a hybrid of both math and String methods. I did the latter. The following:
reads in a String
converts to an int
calculates the number of leading zeroes by using the log10 of the
int and the length of the entered string.
Allocates a StringBuilder to hold the result.
Scanner input = new Scanner(System.in);
String val = input.nextLine();
int numb = Integer.valueOf(val);
int len = val.length();
// exponent of the entered number rounded up to the next int.
// This computes the number of digits in the actual int value.
int exp = (int) Math.log10(numb) + 1;
// now reverse the integer and store in the StringBuilder
StringBuilder sb = new StringBuilder();
while (numb > 0) {
sb.append(numb % 10);
numb /= 10;
}
// and append the leading zeros.
System.out.println(sb + "0".repeat(len - exp));
for input of 00001000
prints 00010000
Note that you are still constrained on input by Integer.MAX_VALUE.
I'm making a program that converts decimal values to binary and vice versa. I've figured out how to convert binary to decimal, however I am having trouble with decimal to binary. I've seen many sources with code on how to do it but most of them involve using an array. I can't use an array because this program has a GUI and JLabel can't print the array. I've found a code that works with certain numbers, but doesn't with others. Here's the code:
public void convertBinary (int decimal)
{
String binary = "";
int remainder;
while (decimal != 0)
{
remainder = decimal % 2;
decimal /= 2;
binary += remainder;
}
lblDecBinAns.setText(String.valueOf(binary));
}
The given number is inputted by the user ("decimal") which is taken when they press the button. I don't know if there's an adjustment that can be made to this code for it to work properly. Perhaps there's an entirely different algorithm that would work for this or maybe a way to print an array with JLabel. I've been stumped on this for a while so any help is appreciated. Thanks.
P.S.
I'm aware of the .toBinary function, but I must create my own method for this one.
You got it done, the only thing you are missing is to REVERSE the binary string
int decimal=10;
String binary = "";
int remainder;
while (decimal != 0)
{
remainder = decimal % 2;
decimal /= 2;
binary += remainder;
}
System.out.println(new StringBuilder(binary).reverse().toString());
yelds
1010 as result
You need to add remainder as binary = remainder + binary or reverse the string. And no need to use String.valueOf since it's already a string. And also consider the case when decimal is zero you need to send 0
public String convertBinary(int decimal) {
String binary = "";
int remainder;
if(decimal == 0) {
return "0";
}
while (decimal != 0) {
remainder = decimal % 2;
decimal /= 2;
binary = remainder + binary;
}
return binary;
}
For a different twist, you can also do it like this.
Initialize the result to an empty string.
Using the AND & operator, mask off the low order bit. You could also use the remainder % operator here too.
Convert the bit, 1 or 0, to a string and prepend it to the result string.
Right shift the number (decimal) by 1 bit so the next bit can be checked.
while(!(decimal>>>1) == 0)
continue the while loop until decimal == 0 (i.e. all 1 bits have been shifted out of the number).
public static String toBinary(int decimal) {
// intialize the string
String binary = Integer.toString(decimal&1);
while ((decimal>>>=1) != 0) {
binary = Integer.toString(decimal&1)+ binary;
// or binary = Integer.toString(decimal % 2) + binary;
}
return binary;
}
Have you tried this?
String test = Integer.toString(n, 2); //n is the number to convert and 2 the base (binary). In case you want an octal number, for example, just change the base to 8.
But using this will cause problem in case you want to reconvert that String into a number just like this:
int number = Integer.parseInt(test); //This will cause NumberFormatException.
To avoid the error, each char of test must be converted to a char
char digit = test.charAt(i);
Finally, convert each char to a individual String again
String converted = String.valueof(digit);
And now you can convert the new String into an int
How to convert binary to decimal i a have code for up to 2 power 10 i need help to 2 power 32
I have tried some other website for the program where i can change to get the appropriate answerer for my coding
{
int [] positionNumsArr= {1,2,4,8,16,32,64,128};//for up to 2 power 8 binary value
int[] numberSplit = new int [8];
Scanner scanNum = new Scanner(System.in);
int count1=0;
int decimalValue=0;
System.out.println("Please enter a positive binary number.(Only 1s and 0s)");
int number = scanNum.nextInt();
while (number > 0)
{
numberSplit[count1]=( number % 10);
if(numberSplit[count1]!=1 && numberSplit[count1] !=0)
{
System.out.println("Was not made of only \"1\" or \"0\" The program will now restart");
main(null);
}
count1++;
number = number / 10;
}
for(int count2 = 0;count2<8;count2++)
{
if(numberSplit[count2]==1)
{
decimalValue=decimalValue+positionNumsArr[count2];
}
}
System.out.print(decimalValue);
}
}
You just need to use Long.parseLong() and specify 2 as the base. Example:
String str = "11101000101";
Long num = Long.parseLong(str, 2); // parse it in base 2, i.e., binary
System.out.print(num); // outputs 1861
This will work up to 263-1 (the max Long value).
Here's a working demo.
I was working on a homework and thought I had finished but the teacher told me that it wasn't what he was looking for so I need to know how I can convert a binary number that is stored as a String to a decimal string without using any built-in function outside of length(), charAt(), power function, and floor/ceiling in Java.
This is what I had on the beginning.
import java.util.Scanner;
public class inclass2Fall15Second {
public static void convertBinaryToDecimalString() {
Scanner myscnr = new Scanner(System.in);
int decimal = 0;
String binary;
System.out.println("Please enter a binary number: ");
binary = myscnr.nextLine();
decimal = Integer.parseInt(binary, 2);
System.out.println("The decimal number that corresponds to " + binary + " is " + decimal);
}
public static void main (String[] args) {
convertBinaryToDecimalString();
}
}
To convert a base 2 (binary) representation to base 10 (decimal), multiply the value of each bit with 2^(bit position) and sum the values.
e.g. 1011 -> (1 * 2^0) + (1 * 2^1) + (0 * 2^2) + (1 * 2^3) = 1 + 2 + 0 + 8 = 11
Since binary is read from right-to-left (i.e. LSB (least significant bit) is on the rightmost bit and MSB (most-significant-bit) is the leftmost bit), we traverse the string in reverse order.
To get the bit value, subtract '0' from the char. This will subtract the ascii value of the character with the ascii value of '0', giving you the integer value of the bit.
To calculate 2^(bit position), we can keep a count of the bit position, and increment the count on each iteration. Then we can just do 1 << count to obtain the value for 2 ^ (bit position). Alternatively, you could do Math.pow(2, count) as well, but the former is more efficient, since its just a shift-left instruction.
Here's the code that implements the above:
public static int convertBinStrToInt(String binStr) {
int dec = 0, count = 0;
for (int i = binStr.length()-1; i >=0; i--) {
dec += (binStr.charAt(i) - '0') * (1 << count++);
}
return dec;
}
As a programming assignment for my java CSC class I have written the following code to convert a number and its base to a decimal number and then to a desired number and base.
public static int baseten(int number,int basein){
int power = 0;
int baseten = 0;
while (number > 0) {
int finalDigit = number % 10;
int product = finalDigit*(int)Math.pow(basein, power);
baseten += product;
number = number / 10;
power++;
}
return(baseten);
}
public static String convert (int decimal, int baseout){
String result = "";
while (decimal > 0){
//if baseout
int remainder = decimal % baseout;
decimal = decimal / baseout;
result = remainder + result;
}
return(result);
}
The question is how to convert a number to a base higher than ten within this code? I assume maybe a char[], but I'm not very good with arrays right now and can't imagine what that might look like. I don't think I can use toString's or parseInt's. Any help would be appreciated. Thanks in advance.
You are almost there. What you could do is insert an if/else statement to determine whether the remainder is greater or equal to ten or not and act accordingly. If it isn't, do what you're doing right now. If it is, then you need to add a char to your string. This char must be (remainder-10) + 65, since 65 is capital A on the ascii table and you need to know how many digits above ten remainder is and add that to A. This could be simplified to simply adding 55, but that is less readable in my opinion. Then, just add that char to the string instead of adding the int.