Java - Convert decimal to binary - Integer - Recursive function - java

Hey I'm really trying to convert decimal int to binary int, without succes.
Please help me.
And I don't want to make it 'System.out.println()' becuase I've already done it.
THANKS!
`I need recursive function that gets decimal int and return binary int
public static void decToBin(int number) {
if(number == 0)
return ;
decToBin(number / 2);
System.out.print(number % 2);
}
That it what I've done...
When I'm trying to get string:
public static String decToBin(int number) {
if(number == 0)
return "";
return new Integer(number % 2).toString() + new Integer(decToBin(number / 2)).toString();
}
Error...

public static String decToBin(int number) {
if(number == 0)
return "";
return new Integer(number % 2).toString() + new Integer(decToBin(number / 2)).toString();
}
This approach has few flaws.
First you can't use "" as argument of new Integer("") because "" holds no value, so you will see NumberFormatException.
Other problem is order of generating result. number % 2 should be placed after result of decToBin(number / 2), just like you are doing it in your first example, where you are printing it after recursive decToBin call
decToBin(number / 2);
System.out.print(number % 2);
Lastly in your return statement you are creating new string, so to generate "100101" you will generate "" "1" "01" "101" 0101" "00101" and then finally "100101". To avoid it use StringBuilder and its append method.

This is a little old, but for the sake of reference and giving a correct answer, this is what you would need to do:
public static String dec2Bin(int num) {
String result = ((num % 2 == 0) ? "0" : "1");
if (num == 0 || num == 1) {
return result;
}
return dec2Bin(num/2) + result;
}

void intToBinary(int num) {
if (num < 2) {
System.out.print(num);
return;
} else {
intToBinary(num / 2);
intToBinary(num % 2);
}
}

import java.io.*;
class Binary{
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number:");
int n = Integer.parseInt(br.readLine());
System.out.print(Integer.toBinaryString(n));
}
}

Related

Reverse String inside a While Loop

I just started learning Java and I'm doing a little program to convert a decimal number into binary numbers using only while loops.
The results were reversed, therefore I'm using a method to reverse the string. But the reverse method does not work for me. Could anyone help me, please?
The following is my code:
import java.util.Scanner;
public class NumberConversion {
public static void main(String[] args) {
Scanner getnumber = new Scanner(System.in);
System.out.print("Enter number: ");
int originalnum = getnumber.nextInt();
int remainder;
String binary_temp;
if (originalnum % 2 != 0) {
while (originalnum > 0) {
remainder = originalnum % 2;
originalnum /= 2;
binary_temp = String.valueOf(remainder);
String binarynum = new StringBuffer(binary_temp).reverse().toString();
System.out.print(binarynum);
}
}
else if (originalnum % 2 == 0) {
while (originalnum > 0) {
originalnum /= 2;
remainder = originalnum % 2;
binary_temp = String.valueOf(remainder);
String binarynum = new StringBuffer(binary_temp).reverse().toString();
System.out.print(binarynum);
}
}
}
}
But the reverse method does not work for me.
That's because you are reversing a string that contains a single digit. If you run your code through a debugger, you will discover that. Every programmer needs to know how to debug code, including code written by other people.
You need to build up the string of binary digits using a single StringBuffer and only after the while loop you reverse the string.
Also, from the code in your question:
if (originalnum % 2 != 0) {
If the above condition is not true, then originalnum % 2 must be zero, hence not need for if-else, i.e. (also from the code in your question):
else if (originalnum % 2 == 0) {
You just need else by itself.
However, you don't need that if-else at all. You just need a single while loop and a single StringBuffer. Actually, for a single-threaded program – such as yours – it is better to use StringBuilder. And rather than creating a new StringBuffer and reversing it on each iteration of the while loop, you can simply insert the [binary] digit.
(More notes after the code.)
import java.util.Scanner;
public class NumberConversion {
public static void main(String[] args) {
Scanner getnumber = new Scanner(System.in);
System.out.print("Enter number: ");
int originalnum = getnumber.nextInt();
originalnum = Math.abs(originalnum);
StringBuilder sb = new StringBuilder();
if (originalnum == 0) {
sb.append('0');
}
else {
while (originalnum > 0) {
int remainder = originalnum % 2;
sb.insert(0, remainder);
originalnum /= 2;
}
}
System.out.println(sb);
}
}
I assume that you only want to handle positive numbers, hence the call to method abs.
The while loop does not handle the case where originalnum is 0 (zero), hence the if (originalnum == 0)
Have you seen Oracle's Java tutorials?
I also recommend the book Java by Comparison by Simon Harrer, Jörg Lenhard & Linus Dietz.
you can use for loop and server your string , here is example
public class StringFormatter {
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
You can use one line to reverse the string
String reversedString = (new StringBuilder().append(oldString).reverse().toString());

Using recursion to add 0 after every even digit

Hello guys,
I would like to share with you my problem. I am practicing recursive methods and i have noticed somewhere one exercise. The exercise is about making the recursive method which adds a 0 to every even digit. If someone has some idea, it would be great if you share here.
the code would be something like this :
public static String adding0AfterEvenNumber(int number) {
String s = String.valueOf(number);
String result;
if (number < 10 && number % 2 == 0) {
return s + 0;
}
}
I am missing the main part of the code but i really do not have an idea how to create it. Thanks in advance
consider this code (comments in line)
// somewhere to store the result
static StringBuilder result = new StringBuilder();
public static void main(String [] args) {
// starting string
String s = "1234567";
// or as
//String s = Integer.toString(1234567);
// call with full string
recurse (s);
// print result
System.out.println("result : " + result.toString());
}
private static void recurse(String s) {
// take first char and add to result
String c = s.substring(0,1);
result.append(c);
// see if even, note no error checking for is a number
if (Integer.parseInt(c) % 2 == 0) {
result.append("0");
}
// then if still has content then strip off first char and call again
if (s.length() > 1)
recurse(s.substring(1));
}
output
result : 1203405607
You would recurse something like this:
public static String adding0AfterEvenNumber(int number) {
return ((number >= 10) ? adding0AfterEvenNumber(number / 10) : "") + String.valueOf(number % 10) + ((number % 2 == 0) ? "0" : "");
}
Try it here.
<script src="//repl.it/embed/JDEV/1.js"></script>
The first part is the terminal condition, appending nothing if there is a single digit number, else calling the recursion after removing the last digit:
(number > 10) ? adding0AfterEvenNumber(number / 10) : "")
The second part appends a zero to the last digit, if even:
String.valueOf(number % 10) + ((number % 2 == 0) ? "0" : "")
I understand that even digits are those digits with an even value not in an even position. The following function should return you a string with the value, although you could return an integer if you shift the head value as many digits as the tail has.
public String add0onEven(int number, int initPos, int endPos) {
if (initPos == endPos - 1) {
int digit = (number / (int) Math.pow(10, initPos)) % 10;
if (digit % 2 == 1) {
return digit + "0";
} else {
return "" + digit;
}
} else if (endPos - initPos < 1) {
return "";
} else {
int sepIdx = (endPos - initPos) / 2 + initPos;
String tail = add0onEven(number, initPos, sepIdx);
String head = add0onEven(number, sepIdx, endPos);
return head + tail;
}
}
You can call the method like this:
add0onEven(1234567, 0, 7)
The output obtained for this invocation:
10230450670
I believe this solution to be better than the substring ones for its lower impact on memory (No need to create a new string on each substring invocation). Besides, it follows a Divide and Conquer approach that suits better to recursivity.

Recursively decompressing a String

I have this assignment that needs me to decompress a previously compressed string.
Examples of this would be
i4a --> iaaaa
q3w2ai2b --> qwwwaaibb
3a --> aaa
Here's what I've written so far:
public static String decompress(String compressedText)
{
char c;
char let;
int num;
String done = "";
String toBeDone = "";
String toBeDone2 = "";
if(compressedText.length() <= 1)
{
return compressedText;
}
if (Character.isLetter(compressedText.charAt(0)))
{
done = compressedText.substring(0,1);
toBeDone = compressedText.substring(1);
return done + decompress(toBeDone);
}
else
{
c = compressedText.charAt(0);
num = Character.getNumericValue(c);
let = compressedText.charAt(1);
if (num > 0)
{
num--;
toBeDone = num + Character.toString(let);
toBeDone2 = compressedText.substring(2);
return Character.toString(let) + decompress(toBeDone) + decompress(toBeDone2);
}
else
{
toBeDone2 = compressedText.substring(2);
return Character.toString(let) + decompress(toBeDone2);
}
}
}
My return values are absolutely horrendous.
"ab" yields "babb" somehow.
"a" or any 1 letter string string yields the right result
"2a" yields "aaaaaaaaaaa"
"2a3b" gives me "aaaabbbbbbbbbbbbbbbbbbbbbbbbbbaaabbbbaaaabbbbbbbbbbbbbbbbbbbbbbbbbb"
The only place I can see a mistake in would probably be the last else section, since I wasn't entirely sure on what to do once the number reaches 0 and I have to stop using recursion on the letter after it. Other than that, I can't really see a problem that gives such horrifying outputs.
I reckon something like this would work:
public static String decompress(String compressedText) {
if (compressedText.length() <= 1) {
return compressedText;
}
char c = compressedText.charAt(0);
if (Character.isDigit(c)) {
return String.join("", Collections.nCopies(Character.digit(c, 10), compressedText.substring(1, 2))) + decompress(compressedText.substring(2));
}
return compressedText.charAt(0) + decompress(compressedText.substring(1));
}
As you can see, the base case is when the compressed String has a length less than or equal to 1 (as you have it in your program).
Then, we check if the first character is a digit. If so, we substitute in the correct amount of characters, and continue with the recursive process until we reach the base case.
If the first character is not a digit, then we simply append it and continue.
Keep in mind that this will only work with numbers from 1 to 9; if you require higher values, let me know!
EDIT 1: If the Collections#nCopies method is too complex, here is an equivalent method:
if (Character.isDigit(c)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Character.digit(c, 10); i++) {
sb.append(compressedText.charAt(1));
}
return sb.toString() + decompress(compressedText.substring(2));
}
EDIT 2: Here is a method that uses a recursive helper-method to repeat a String:
public static String decompress(String compressedText) {
if (compressedText.length() <= 1) {
return compressedText;
}
char c = compressedText.charAt(0);
if (Character.isDigit(c)) {
return repeatCharacter(compressedText.charAt(1), Character.digit(c, 10)) + decompress(compressedText.substring(2));
}
return compressedText.charAt(0) + decompress(compressedText.substring(1));
}
public static String repeatCharacter(char character, int counter) {
if (counter == 1) {
return Character.toString(character);
}
return character + repeatCharacter(character, counter - 1);
}

Trying to recursively convert an integer to binary in String format in Java?

The following code works when I just want to print the digits out instead of saving them in a String variable:
public static void toBinary(int num) {
if (num>0) {
toBinary(num/2);
System.out.print(num%2 + " ");
}
}
However, what I'm trying to do is to append each binary digit to the end of a String. The method I have to do this is:
public static String toBinary(int num){
String binary = "";
if(num > 0){
toBinary(num/2);
binary += (num%2);
}
return binary;
}
Regardless of the number passed in for this method, the String ends up being a single 1 or 0. I thought that the logic would be the same, which apparently is wrong. Any help?
Assign return value of toBinary() method to binary variable :
if(num > 0){
binary = toBinary(num/2);
binary += (num%2);
}
Note: Generation of binary string is very easy in Java
e.g.
System.out.println(Integer.toBinaryString(23));
Output:
10111
The problem with your attempt at recursion is that you are initialising the binary variable at every level and so you don't get the full result of the recursion. You will only ever get the last digit. It will get passed back up the recurse chain at the very end.
The recursive equivalent of your original method would be something like the following:
public static String toBinary(int num) {
if (num>0)
return toBinary(num / 2) + (num % 2);
else
return "";
}
Note that both this and the original are not very good binary converters because they don't handle 0 properly. Nor do they handle negative numbers.
We can fix for 0, and gracefully handle negative numbers like so:
public static String toBinary(int num) {
if (num < 0)
throw new IllegalArgumentException("Negative numbers not supported");
else if (num == 0)
return "0";
else return toBinaryInternal(num);
}
private static String toBinaryInternal(int num) {
if (num>0)
return toBinaryInternal(num / 2) + (num % 2);
else
return "";
}

Printing a number with appropriate commas recursively

A sample input of 12345 should return 12,345. I have it figured out i think. Only problem is the string I get is reversed (543,21). Now i know there's ways to reverse a string pretty easily but that's more complexity to the running time so I was wondering if there was a straightforward way to do it within the auxiliary itself?
public void print(int n){
String number = Integer.toString(n);
StringBuilder answer = new StringBuilder();
if(number.length() > 3){ //Only worry about adding commas if its more than three digits
printAux(number, answer, 1, number.length()-1);
System.out.println(answer);
}
}
private void printAux(String s, StringBuilder answer, int count, int index){
if(index < 0){
return;
}
else{
//If the counter is at the 4th index meaning it has passed three digits
if(count%3 == 1 && count > 3){
answer.append(",");
index = index + 1;
count = 0;
}
else{
answer.append(s.charAt(index));
}
printAux(s, answer, count + 1, index - 1);
}
}
Something simpler
public static void print(String s) {
out.print(s.charAt(0));
if (s.length() == 1) out.print("\n");
else {
if (((s.length()-1) % 3) == 0) out.print(",");
print(s.substring(1));
}
}
Explanation:
always print the 1st character
if there is no more character, print CR
if there is at least one character to process, check if the length of what to process is a multiple of 3, if yes print a ","
and call recursively print with the string minus the 1st character
You can can use StringBuilder.reverse() to reverse a String in one line like
String str = "abc";
str = new StringBuilder(str).reverse().toString();
But you could also use printf1. Something like,
public static void print(int n) {
System.out.printf("%,d%n", n);
}
public static void main(String[] args) {
int num = 123456789;
print(num);
}
Output is (as requested)
123,456,789
1See also The Java Tutorials - Formatting Numeric Print Output for more options.
You can use the following DecimalFormat to get the job done.
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));

Categories

Resources