import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and when you are finished enter '=' ");
System.out.print("Enter the first number: ");
ArrayList<String> my_list = new ArrayList<String>();
String value = scanner.next();
int num = Integer.parseInt(value);
if (num == Integer.parseInt(value)) {
my_list.add(value);
} else {
System.out.print("Please enter a number");
}
while (!value.equals("=")) {
System.out.print("Enter a number: ");
value = scanner.next();
my_list.add(value);
my_list.remove("=");
}
System.out.println("The list looks like: ");
System.out.println(my_list);
backarryToNum(my_list);
}
public static void reverseArrayToNum(ArrayList number){
int num;
int sum = 0;
for (int i = number.size()-1; i >= 0 ; i--) {
int n = number.get(i);
num = n * (int)Math.pow(10,i);
sum += num;
System.out.println(sum);
}
}
}
The "int n = number.get(i)" line is the problem.
The method reverseArrayToNum will make the array reverse and will make the reversed array of numbers covert to a number.
Just change
int n = number.get(i);
to
int n = Integer.parseInt((String) number.get(i));
otherwise you try to store a String into an int.
Also, I suppose
backarryToNum(my_list);
is supposed to be
reverseArrayToNum(my_list);
I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps
I have an assignment to break an integer into it's individual digits, report them back to the user, and add them. I can do that, but I'm struggling with supporting negative integers. Here's my code, which works exactly the way I want it to, but only for positive integers:
import java.util.*;
public class Module4e
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i]);
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
I've found plenty of hints for getting this to work with positive integers, but none for negatives.
Use RegExp
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestDigits {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Validate Input
String number = console.nextLine();
Pattern p = Pattern.compile("(-?[0-9]{1})+");
Matcher m = p.matcher(number);
if (!m.matches()) {
throw new IllegalArgumentException("Invalid Numbers");
}
// Calculate
p = Pattern.compile("-?[0-9]{1}+");
m = p.matcher(number);
int result = 0;
System.out.print("The digits of the number are: ");
while (m.find()) {
System.out.print(m.group() + " ");
result += Integer.valueOf(m.group());
}
System.out.println("");
System.out.println("Result " + result);
}
}
// I think you can use this code //also you can multiply the number by -1
int positive = 0;
//positive give you information about the number introduced by the user
if (myNum.charAt(0)=='-'){
positive=1;
}else{
positive=0;
for (int i=positive; i<myNum.length(); i++){
//be carefull with index out of bound exception
if ((i+1)<myNum.length()){
upNum[i]=myNum.substring(i,i+1);
}
}
Change the statement String myNum=console.nextLine() to String myNum = String.valueOf(Math.abs(Integer.valueOf(console.nextLine())));
You do not have to use String to solve this problem. Here's my thought.
import java.util.*;
public class Module4e throws IllegalArgumentException {
static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
if (!console.hasNextInt()) throw new IllegalArgumentException();
int myNum=console.nextInt();
myNum = Math.abs(myNum);
int sum=0;
System.out.println("\n");
System.out.print("The digits of the number are: ");
While (myNum > 10) {
System.out.print(myNum % 10);
System.out.print(" ");
sum += myNum % 10;
myNum /= 10;
}
System.out.println(myNum);
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
Try this. I gave -51 as input and got -6 as output. This is what you are looking for?
import java.util.*;
public class LoggingApp
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
int multiple = 1;
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
Integer myNumInt = Integer.parseInt(myNum);
if (myNumInt < 1){
multiple = -1;
myNum = Integer.toString(myNumInt*-1);
}
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i])*multiple;
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
Trying to figure out how I would take any amount of inputted numbers from a user and add them together
Example user input: 1 2 3 4
Sum = 10
The user can put any amount of numbers in not a specified amount so if he wanted to add 1 2 3 4 5 6 7 8 9 10 11 12 13, it would sum them all up to 91
Thanks for the help in advance.
import java.util.Scanner;
public class test
{
public static final int SENTINEL = -1;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
while (score >= 0) {
if (score <= -1) {
score = kb.nextInt();
sum += score;
score = 0;
}
System.out.println(sum);
}
}
}
Thanks to libik for all his time and help, here is the finished code.
import java.util.Scanner;
public class JavaApplication1156 {
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
if (sum <= -1)
System.out.println("Application ended");
else if (sum >= 0)
System.out.println("Sum = " + sum);
} while (sum != -1);
}
}
It is very easy actually
import java.util.Scanner;
public class JavaApplication115 {
public static void main(String[] args) {
System.out.println("write numbers, if you write zero, program ends");
Scanner input = new Scanner(System.in); //just copy-and paste this line, you dont have to understand it yet.
int number;
int sum = 0;
do {
number = input.nextInt(); //this reads number from input and store its value in variable number
sum+= number; //here you add number to the total sum
} while(number != 0); //just repeat cycle as long as number is not zero
System.out.println("Sum is : " + sum);
}
}
Working code based on your code :
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println(sum);
}
Also if you are interested in "minimal" version, which is the same as the one before, but using as less code as possible, here it is :
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter numbers here");
Scanner kb = new Scanner((new Scanner(System.in)).nextLine()); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
sum += kb.nextInt();
}
System.out.println(sum);
}
Find sum of each line as long as sum is not zero (based on second block of code) :
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println("Sum = " + sum);
} while (sum != 0);
}
//Input the number in a single line (but be in size limit of integer)
import java.util.Scanner;
public class Sum_of_integers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0;
while(num >= 1) { //base value
int lastval = num % 10; //the logic
num = num / 10;
sum += lastval;
}
System.out.println(sum);
}
}
Question - Keep taking numbers as inputs till the user enters ‘x’, after that print sum of all.
Scanner sc = new Scanner(System.in);
int input = 0;
int sum = 0;
while (true){
sum = sum+input;
if (input==5){
System.out.println("Loop is stopped");
System.out.println("The sum is " + sum);
break;
}
else {
System.out.println("Take the inputs");
input = sc.nextInt();
}
}
I am trying to convert decimal to binary numbers from the user's input using Java.
I'm getting errors.
package reversedBinary;
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));
}
}
private static Object binaryform(int number) {
int remainder;
if (number <=1) {
System.out.print(number);
}
remainder= number %2;
binaryform(number >>1);
System.out.print(remainder);
{
return null;
} } }
How do I convert Decimal to Binary in Java?
Integer.toBinaryString() is an in-built method and will do quite well.
Integer.toString(n,8) // decimal to octal
Integer.toString(n,2) // decimal to binary
Integer.toString(n,16) //decimal to Hex
where n = decimal number.
Your binaryForm method is getting caught in an infinite recursion, you need to return if number <= 1:
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);
}
}
I just want to add, for anyone who uses:
String x=Integer.toBinaryString()
to get a String of Binary numbers and wants to convert that string into an int. If you use
int y=Integer.parseInt(x)
you will get a NumberFormatException error.
What I did to convert String x to Integers, was first converted each individual Char in the String x to a single Char in a for loop.
char t = (x.charAt(z));
I then converted each Char back into an individual String,
String u=String.valueOf(t);
then Parsed each String into an Integer.
Id figure Id post this, because I took me a while to figure out how to get a binary such as 01010101 into Integer form.
/**
* #param no
* : Decimal no
* #return binary as integer array
*/
public int[] convertBinary(int no) {
int i = 0, temp[] = new int[7];
int binary[];
while (no > 0) {
temp[i++] = no % 2;
no /= 2;
}
binary = new int[i];
int k = 0;
for (int j = i - 1; j >= 0; j--) {
binary[k++] = temp[j];
}
return binary;
}
public static void main(String h[])
{
Scanner sc=new Scanner(System.in);
int decimal=sc.nextInt();
String binary="";
if(decimal<=0)
{
System.out.println("Please Enter greater than 0");
}
else
{
while(decimal>0)
{
binary=(decimal%2)+binary;
decimal=decimal/2;
}
System.out.println("binary is:"+binary);
}
}
The following converts decimal to Binary with Time Complexity : O(n) Linear Time and with out any java inbuilt function
private static int decimalToBinary(int N) {
StringBuilder builder = new StringBuilder();
int base = 2;
while (N != 0) {
int reminder = N % base;
builder.append(reminder);
N = N / base;
}
return Integer.parseInt(builder.reverse().toString());
}
In C# , but it's just the same as in Java :
public static void findOnes2(int num)
{
int count = 0; // count 1's
String snum = ""; // final binary representation
int rem = 0; // remainder
while (num != 0)
{
rem = num % 2; // grab remainder
snum += rem.ToString(); // build the binary rep
num = num / 2;
if (rem == 1) // check if we have a 1
count++; // if so add 1 to the count
}
char[] arr = snum.ToCharArray();
Array.Reverse(arr);
String snum2 = new string(arr);
Console.WriteLine("Reporting ...");
Console.WriteLine("The binary representation :" + snum2);
Console.WriteLine("The number of 1's is :" + count);
}
public static void Main()
{
findOnes2(10);
}
It might seem silly , but if u wanna try utility function
System.out.println(Integer.parseInt((Integer.toString(i,2))));
there must be some utility method to do it directly, I cant remember.
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
System.out.print("Put a number : ");
int a=in.nextInt();
StringBuffer b=new StringBuffer();
while(a>=1)
{
if(a%2!=0)
{
b.append(1);
}
else if(a%2==0)
{
b.append(0);
}
a /=2;
}
System.out.println(b.reverse());
}
Binary to Decimal without using Integer.ParseInt():
import java.util.Scanner;
//convert binary to decimal number in java without using Integer.parseInt() method.
public class BinaryToDecimalWithOutParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
int binarynum =input.nextInt();
int binary=binarynum;
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
System.out.println("Binary="+binarynum+" Decimal="+decimal); ;
}
}
Output:
Enter a binary number:
1010
Binary=1010 Decimal=10
Binary to Decimal using Integer.parseInt():
import java.util.Scanner;
//convert binary to decimal number in java using Integer.parseInt() method.
public class BinaryToDecimalWithParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
String binaryString =input.nextLine();
System.out.println("Result: "+Integer.parseInt(binaryString,2));
}
}
Output:
Enter a binary number:
1010
Result: 10
A rather simple than efficient program, yet it does the job.
Scanner sc = new Scanner(System.in);
System.out.println("Give me my binaries");
int str = sc.nextInt(2);
System.out.println(str);
All your problems can be solved with a one-liner!
To incorporate my solution into your project, simply remove your binaryform(int number) method, and replace System.out.print(binaryform(number)); with System.out.println(Integer.toBinaryString(number));.
/**
* converting decimal to binary
*
* #param n the number
*/
private static void toBinary(int n) {
if (n == 0) {
return; //end of recursion
} else {
toBinary(n / 2);
System.out.print(n % 2);
}
}
/**
* converting decimal to binary string
*
* #param n the number
* #return the binary string of n
*/
private static String toBinaryString(int n) {
Stack<Integer> bits = new Stack<>();
do {
bits.push(n % 2);
n /= 2;
} while (n != 0);
StringBuilder builder = new StringBuilder();
while (!bits.isEmpty()) {
builder.append(bits.pop());
}
return builder.toString();
}
Or you can use Integer.toString(int i, int radix)
e.g:(Convert 12 to binary)
Integer.toString(12, 2)
public static String convertToBinary(int dec)
{
String str = "";
while(dec!=0)
{
str += Integer.toString(dec%2);
dec /= 2;
}
return new StringBuffer(str).reverse().toString();
}
Practically you can write it as a recursive function. Each function call returns their results and add to the tail of the previous result. It is possible to write this method by using java as simple as you can find below:
public class Solution {
private static String convertDecimalToBinary(int n) {
String output = "";
if (n >= 1) {
output = convertDecimalToBinary(n >> 1) + (n % 2);
}
return output;
}
public static void main(String[] args) {
int num = 125;
String binaryStr = convertDecimalToBinary(num);
System.out.println(binaryStr);
}
}
Let us take a look how is the above recursion working:
After calling convertDecimalToBinary method once, it calls itself till the value of the number will be lesser than 1 and return all of the concatenated results to the place where it called first.
References:
Java - Bitwise and Bit Shift Operators https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
If you want to reverse the calculated binary form , you can use the StringBuffer class and simply use the reverse() method . Here is a sample program that will explain its use and calculate the binary
public class Binary {
public StringBuffer calculateBinary(int number) {
StringBuffer sBuf = new StringBuffer();
int temp = 0;
while (number > 0) {
temp = number % 2;
sBuf.append(temp);
number = number / 2;
}
return sBuf.reverse();
}
}
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("enter the number you want to convert");
BufferedReader bReader = new BufferedReader(newInputStreamReader(System.in));
int number = Integer.parseInt(bReader.readLine());
Binary binaryObject = new Binary();
StringBuffer result = binaryObject.calculateBinary(number);
System.out.println(result);
}
}
The better way of doing it:
public static void main(String [] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine().trim());
double ans = 0;
int i=0;
while(t!=0){
int digit = t & 1;
ans = ans + (digit*Math.pow(10,i));
i++;
t =t>>1;
}
System.out.println((int)ans);
}
I just solved this myself, and I wanted to share my answer because it includes the binary reversal and then conversion to decimal. I'm not a very experienced coder but hopefully this will be helpful to someone else.
What I did was push the binary data onto a stack as I was converting it, and then popped it off to reverse it and convert it back to decimal.
import java.util.Scanner;
import java.util.Stack;
public class ReversedBinary
{
private Stack<Integer> st;
public ReversedBinary()
{
st = new Stack<>();
}
private int decimaltoBinary(int dec)
{
if(dec == 0 || dec == 1)
{
st.push(dec % 2);
return dec;
}
st.push(dec % 2);
dec = decimaltoBinary(dec / 2);
return dec;
}
private int reversedtoDecimal()
{
int revDec = st.pop();
int i = 1;
while(!st.isEmpty())
{
revDec += st.pop() * Math.pow(2, i++);
}
return revDec;
}
public static void main(String[] args)
{
ReversedBinary rev = new ReversedBinary();
System.out.println("Please enter a positive integer:");
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
{
int input = Integer.parseInt(sc.nextLine());
if(input < 1 || input > 1000000000)
{
System.out.println("Integer must be between 1 and 1000000000!");
}
else
{
rev.decimaltoBinary(input);
System.out.println("Binary to reversed, converted to decimal: " + rev.reversedtoDecimal());
}
}
}
}
import java.util.*;
public class BinaryNumber
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number");
int n = scan.nextInt();
int rem;
int num =n;
String str="";
while(num>0)
{
rem = num%2;
str = rem + str;
num=num/2;
}
System.out.println("the bunary number for "+n+" is : "+str);
}
}
This is a very basic procedure, I got this after putting a general procedure on paper.
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number:");
int number = input.nextInt();
while(number!=0)
{
if(number%2==0)
{
number/=2;
System.out.print(0);//Example: 10/2 = 5 -> 0
}
else if(number%2==1)
{
number/=2;
System.out.print(1);// 5/2 = 2 -> 1
}
else if(number==2)
{
number/=2;
System.out.print(01);// 2/2 = 0 -> 01 ->0101
}
}
}
}
//converts decimal to binary string
String convertToBinary(int decimalNumber){
String binary="";
while(decimalNumber>0){
int remainder=decimalNumber%2;
//line below ensures the remainders are reversed
binary=remainder+binary;
decimalNumber=decimalNumber/2;
}
return binary;
}
One of the fastest solutions:
public static long getBinary(int n)
{
long res=0;
int t=0;
while(n>1)
{
t= (int) (Math.log(n)/Math.log(2));
res = res+(long)(Math.pow(10, t));
n-=Math.pow(2, t);
}
return res;
}
Even better with StringBuilder using insert() in front of the decimal string under construction, without calling reverse(),
static String toBinary(int n) {
if (n == 0) {
return "0";
}
StringBuilder bldr = new StringBuilder();
while (n > 0) {
bldr = bldr.insert(0, n % 2);
n = n / 2;
}
return bldr.toString();
}
No need of any java in-built functions. Simple recursion will do.
public class DecimaltoBinaryTest {
public static void main(String[] args) {
DecimaltoBinary decimaltoBinary = new DecimaltoBinary();
System.out.println("hello " + decimaltoBinary.convertToBinary(1000,0));
}
}
class DecimaltoBinary {
public DecimaltoBinary() {
}
public int convertToBinary(int num,int binary) {
if (num == 0 || num == 1) {
return num;
}
binary = convertToBinary(num / 2, binary);
binary = binary * 10 + (num % 2);
return binary;
}
}
int n = 13;
String binary = "";
//decimal to binary
while (n > 0) {
int d = n & 1;
binary = d + binary;
n = n >> 1;
}
System.out.println(binary);
//binary to decimal
int power = 1;
n = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
n = n + Character.getNumericValue(binary.charAt(i)) * power;
power = power * 2;
}
System.out.println(n);