This question already has answers here:
Converting Decimal to Binary Java
(26 answers)
Closed 6 years ago.
How can we convert int number, a decimal, to Binary? I'm learning Java & have the code below. Any advice? Thanks!
public static int decimalToBinary(int number) {
int result = 0;
while(number > 0){
int mod = number % 2;
result = result * 1 + mod;
number /= 2;
}
return result;
}
You can use the Integer.toBinaryString() method as follows,
int n = 100;
System.out.println(Integer.toBinaryString(n));
The Integer.toBinaryString() takes an int as a parameter and returns a String, so you can also do the following:
int n=100;
String s = Integer.toBinaryString(n);
System.out.println(s);
This will print it out to the screen, but you can just as easily assign it to a variable.
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);
}
}
Related
I tried to create a code to take in a whole number in Java and output it in binary. The problem would seem that the binary is printing out backward. For instance, 6 should output as 011 but comes out as 110.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner in =new Scanner(System. in );
userNum = in.nextInt();
binary(userNum);
System.out.print("\n");
}
private static void binary(int userNum) {
int remainder;
while (userNum <= 1) {
System.out.print(userNum);
return;
}
remainder = userNum % 2;
binary(userNum >> 1);
System.out.print(remainder);
}
}
I tried incorporating a push stack to push the remainder into a stack that I can pull later, but couldn't quite get it to land.
private static void reverse(int userNum) {
String backwards;
while (userNum >= 0) {
backwards.push(int userNum);
System.out.println(backwards);
return;
}
}
It is part of a class assignment which asks the following.
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:
As long as x is greater than 0
Output x % 2 (remainder is either 0 or 1)
x = x / 2
Note: The above algorithm outputs the 0's and 1's in reverse order.
Ex: If the input is:
6
the output is:
011
6 in binary is 110; the algorithm outputs the bits in reverse.
These are the tests the program applies and my results.
Input 6
Your output binary is:110
Expected output 011
Input 19
Your output 10011
Expected output 11001
Input 255
Your output 11111111
Expected output 11111111
Any help or guidance in this, I would be greatly appreciative of it.
Per the requirement and not taking into consideration of negative numbers
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
while(userNum > 0){
System.out.print(userNum % 2);
userNum = userNum / 2;
}
System.out.print("\n");
}
}
First using predefined method then a custom one.
public class IntToBinary {
public static void main(String[] args) {
int decimalNumber = 10;
System.out.println(Integer.toBinaryString(decimalNumber));
System.out.println(convertBinary(10));
}
public static String convertBinary(int num) {
StringBuilder sb = new StringBuilder();
int binary[] = new int[40];
int index = 0;
while (num > 0) {
binary[index++] = num % 2;
num = num / 2;
}
for (int i = index - 1; i >= 0; i--) {
sb.append(binary[i]);
}
return sb.toString();
}
}
Your program appears to work fine for positive values. However it does not handle negative numbers which have their own unique binary representation known as two's complement. You could do something like the following to accommodate:
private static void binary(int userNum) {
int remainder;
// while (userNum <= 1) {
// System.out.print(userNum);
// return;
// }
if (userNum == 0) {
return;
}
// simply mask off the bit instead of dividing by two
remainder = userNum & 1;
// and shift right thru the sign bit
binary(userNum >>> 1);
System.out.print(remainder);
}
}
binary(-6));
prints
11111111111111111111111111111010
And the reason these printed out in proper order is because your routine is recursive. That is a natural behavior of printing the values stored in the stack from a recursive procedure.
import java.util.Scanner;
public class Reverse_BinaryNum {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
int inputNum;
System.out.println("Enter the Digit : ");
inputNum = scnr.nextInt();
System.out.println("The Reverse Binary for the given Digit is : ");
while (inputNum > 0) {
System.out.print(inputNum % 2);
inputNum = inputNum / 2;
}
scnr.close();
}
}
I want to reverse a number without using array.I want to know how would I save the number.I think for this step I need to also know whether the number is one digit or two digit etc.
Below is my code what I did.
#Edit
I have solved this problem by following method
public class ReverseNumber
{
public static void main(String[] args)
{
ReverseNumber obj = new ReverseNumber();
int result = obj.reverse(2199);
System.out.println(result);
}
public int reverse(int num)
{
int rnum1=0;
for(int i=num;i!=0;)
{
rnum1=(rnum1*10)+(i%10);
i=i/10;
// write your code here
}
return rnum1;
}
}
you almost had it! you're only missing the part where you need to multiply num1 with 10, and the choice of the loop is a bit unlucky:
public static int reverse(int num) {
int input = num;
int num1 = 0;
while (input>0) {
num1 = num1 * 10;
num1 = num1 + input%10;
input = input / 10;
}
return num1;
}
EDIT: had a mistake in the implemetation... now it's fixed
#Parker_Halo provided an excellent iterative solution. I am adding here a recursive solution for completeness:
public static int reverse(int number, int n) {
if (number == 0)
return n;
return reverse(number / 10, n * 10 + number % 10);
}
You would call it like this :
int rev = reverse(num, 0);
This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 7 years ago.
Below is a code that I have for flipping a given integer and displaying the flipped results. It runs but I have issues for when the number is smaller than two digits. It obviously cannot be flipped. I wanted to make the loop an if else stating "if number is two digits or more reverse." "Else state that the integer needs to be two or more digits." how could I go about this?
import java.util.Scanner;
public class ReverseInteger {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer that you would like to have reversed: ");
int number = input.nextInt();
reverse(number);
}
public static void reverse(int userInteger)
{
int tempDigit = 0;
while (userInteger > 0){
tempDigit = userInteger % 10;
System.out.print(tempDigit);
userInteger = userInteger / 10;
}
}
}
I am trying to get it to understand that 01 can be converted to 10. This would need to be done by the code understanding that the userInteger is more than one digit but I cant seem to figure out how to do that... Any ideas on how I can get this to check for two digits and execute the loop accordingly would be appreciated!
public static void reverse(int n)
{
int temp = 0;
int count = 0;
while(n != 0)
{
if(n%10 == 0)count++;
temp = temp*10 + n %10;
n /= 10;
}
for(int i = 0; i < count; i++)
{
System.out.print(0);
}
System.out.println(temp);
}
Convert the int to a String using Integer.toString method and save it to a string. Declare a String that will be later used as output. Start a for loop that goes through the number ( which was converted to a String) from its end to its beginning. It add each character from end to start to the output String. This results in the output String to be the reverse of the number String. Then just simply convert the output String using Integer.parseInt method and return the int value.
The code should look like:
public static int reverse(int n)
{
String number = Integer.toString(n);
String output;
for(int i = number.length()-1; i >= 0; i--)
output += number.charAt(i);
return Integer.parseInt(output);
}
I recommend using String.valueof(int).toCharArray(); and looping through in reverse to compose a new char[]. Then use Integer.parseInt(String);
Im having trouble converting binary to a decimal. We have to use a function for the conversion and do it by hand rather than use a predefined function. This is what I have so far, I know it is a mess but I am stuck on how to fix it. Thanks!
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (!"-1".equals(inString)) {
int i;
int binaryLength;
binaryLength = inString.length();
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
System.out.println(decimal);
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
To use a function, as your assignment requires, you have to write the function outside the main method, and then include a statement that calls the function. So move this above the line that says public static void main:
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, each function or method (including main) has its own variables that it uses, called local variables; but the local variables that each function uses are its own separate copies. Thus, the above function won't be able to use the binaryLength or decimal variabes belonging to main. You'll need to declare them inside binaryToDecimal:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, this function won't be able to access main's inString, but the idea is that you've given the function the string you want to work with, which it refers to as binaryString. So change inString to binaryString in the function:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal = decimal + Math.pow(2,binaryString.length() - 1 - i);
}
return (int) decimal;
}
And also note that the binaryLength and decimal variables are totally unrelated to the variables of the same name in main. That means that when you assigned binaryLength in main, that has no effect on binaryLength in binaryToDecimal. You'll need to assign it in the function. Change int binaryLength; to
int binaryLength = binaryString.length();
Finally, in order to use the function, main will need to call it. Put this in the main function:
decimal = binaryToDecimal(inString);
When main executes that, it will call the function and tell it to work with inString. The function will call that binaryString, though. The function will return a result, and then main will assign that result to the variable decimal--that means the local variable decimal that belongs to main, since the above statement is inside main.
I don't know if this will make your whole program work. (It should, but I'm not sure.) But I'm just trying to explain the details of how to use functions.
The confusing part is with the Math.pow, and its complicated arguments, where off-by-one errors are easily made.
Yet, if we have a number at base 10, like
123
its value is
(((0*10)+1)*10+2)*10+3
This looks complex, but note the easy pattern: Starting out with 0, we go through the digits. As long as we have another dgit, we multiply the previous result by the base and add the digit value. That's all! No Math.pow, no complex index calculations.
Hence:
String s = "1010";
int value = 0;
int base = 2;
for (i=0; i < s.length(); s++) {
char c = s.charAt(i);
value = value * base;
value = value + c - '0';
}
When I cleaned up your code, it worked just fine -
public static int binaryToDecimal(String binaryString) {
int binaryLength = binaryString.length();
int decimal = 0;
for (int i = binaryLength - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1') {
decimal += Math.pow(2, binaryLength - 1 - i);
}
}
return decimal;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String inString = input.nextLine();
while (!"-1".equals(inString)) {
System.out.println(binaryToDecimal(inString));
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
Output
Enter a binary number:
01
1
Enter a binary number:
10
2
Enter a binary number:
-1
All set !
Here's the function after a little clean up.
public static int binaryToDecimal (String binaryString) {
int decimal = 0;
int base = 2;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal += Math.pow(base,i);
}
return decimal;
}
I'm supposed to use a recursive method to print out the digits of a number vertically.
For example, if I were to key in 13749, the output would be:
1
3
7
4
9
How should I approach this question?? It also states that I should use the if/else method to check for the base case.. I just started learning java and I'm not really good at it :(
import java.util.Scanner;
public class test2 {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
System.out.println();
System.out.println(numbers(n));
}
public static int numbers(int n){
int sum;
if (n == 0) {
sum = 1;
} else {
System.out.println(n%10);
sum = numbers(n / 10) + (n % 10);
}
return sum;
}
}
Here is my code in C++
Just modify it for Java. You need to show the number after you call the function that way you show the last one first... as per the answer from s.ts
void recursive(int n) {
if (n < 10)
cout << n << endl;
else
{
recursive(n / 10);
cout << n % 10 << endl;
}
}
I was asked this question today in an interview!
public class Sandbox {
static void prints(int d) {
int rem = d % 10;
if (d == 0) {
return;
} else {
prints(d / 10);
}
System.out.println(rem);
}
public static void main(String[] args) {
prints(13749);
}
}
Output:
1
3
7
4
9
You asked how to approach this, so I'll give you a tip: it would be a lot easier to build up the stack and then start printing output. It also doesn't involve manipulating strings, which is a big plus in my book. The order of operations would be:
Check for base case and return if it is
Recursive call
Print
This way when you get to the base case, you'll start printing from the tail to the head of the calls:
recursive call 1
recursive call 2
recursive call 3
.... reached base case
print 3
print 2
print 1
This way you can simply print number % 10 and make the recursive call with number / 10, the base case would be when number is 0.
class PrintDigits {
public static void main(String[] args) {
String originalNumber, reverse = "";
// Creating an Scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter a number:");
// Reading an input
originalNumber = in.nextLine();
// Calculating a length
int length = originalNumber.length();
// Reverse a given number
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + originalNumber.charAt(i);
//System.out.println("Reverse number: "+reverse);
digits(Integer.parseInt(reverse));
}
/* digits of num */
public static void digits(int number) {
if (number == 0)
System.out.println("");
else {
int mode=10;
System.out.println(+number%mode);
digits(number/mode);
}
}
}
If number consists of more than one digit print ( n / 10 )
print ( n % 10 )
If you want them printed in the other order
print ( n % 10 )
If number consists of more than one digit print ( n / 10 )
try this
public class Digits {
public static void main(String[] args) {
printDigits(13749);
}
private static void printDigits(Integer number) {
int[] m = new int[number.toString().toCharArray().length];
digits(number, 0, m, 0);
for (int i= m.length - 1; i>=0; i--) {
System.out.println(m[i]);
}
}
public static int digits(int number, int reversenumber, int[] m, int i) {
if (number <= 0) {
return reversenumber;
}
m[i] = (number % 10);
reversenumber = reversenumber * 10 + (number % 10);
return digits(number/10, reversenumber, m, ++i);
}
}
Python example
def printNoVertically(number):
if number < 9:
print(number)
return
else:
printNoVertically(number/10)
print(number % 10)