Print Binary using recursion [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This code work properly. I need help to change this into int function. Please don't add extra int or void function to it.
public void binary(int n) {
if(n==0)
return;
binary(n>>1);
System.out.printf("%d",n%2);
}

Here is the changed code:
public int binary(int n)
{
if (n == 0 || n == 1) return n;
return binary(n >> 1) * 10 + n % 2;
}
It returns an int and it will return binary form of the number. This code will fail to provide correct output after the number 1023. The binary of 1023 is 1111111111.
After this, any number you enter will cause overflow issues and you will receive a wrong output. You can further increase the range of the program if you use long. However, that too will fail to provide any correct output after 524287 for the same reasons mentioned before.
You can use BigInteger class if you want to store binary of any numbers bigger than 524287.

Related

i am not getting any error in my java code but still it is unable to run? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I don't know why my defined function is not working smoothly.
in this I am trying to build a function to convert a binary number to a decimal number
public class binarrytodec {
public static void bintodec(int n){
int p=0;
int dec=0;
while(n>0){
int ld=n%10;
dec = dec + (ld*(int)Math.pow(2, p));
p++;
n=n%10;
}
System.out.print(dec);
}
public static void main(String args[]) {
bintodec(1110001);
}
}
% is not division, it's a remainder operation - it shows how much is left after integer division. 1 % 10 == 1. Thus your n is never becoming 0, and your code enters an infinite loop.

Using ASCII to find valid Anagram [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
Why doesn't this solution work for finding valid anagram?
26/36 test cases get passed in LeetCode.
class Solution {
public boolean isAnagram(String s, String t) {
int sASCII = 0, tASCII = 0;
if(s.length() != t.length()) {return false;}
else{
for(int i = 0 ; i < s.length(); i++){
sASCII += (int)s.charAt(i);
tASCII += (int)t.charAt(i);
}
}
if(sASCII == tASCII){
return true;
}
return false;
}
}
The sums tASCII and sASCII can be equal even if the numbers are not anagrams. Let's say that you can get the number 100 by adding 60+40, but you can also get it by adding 70+30, so i recommend to use a HashMap to note every occurence of every letter or to sort the strings as arrays of chars and then compare them.

How can I store characters of string variable in an integer array in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
For example if:
String str = "100101010";
Then following should happen:
a[0]=1
a[1]=0
a[2]=0
...
It should hold for large strings also (up to 64 characters).
One hint: find a chart for ASCII. http://www.asciitable.com/index/asciifull.gif The code for "0" is 48 and the code for "1" is 49. You can convert characters to numbers just by subtracting 48 from the ASCII value.
int value = str.charAt(0) - 48;
It's important to realize that a Java char is just an integer type just like int and byte. You can do math with them. With that idea in mind, you should be able figure out the rest yourself.
(This is technically a duplicate since I answered a similar question long ago, but I can't find it, so you get a freebie.)
public static int[] getAsArray(String value){
// not null ; not empty ; contains only 0 and 1
if(value == null || value.trim().length()<1 || !value.matches("[0-1]+")){
return new int[0];
}
//if it necessary !value.matches("[0-1]+" regex to validate
value = value.trim();
value = value.length()>64 ? value.substring(0,63) : value;// up to 64 characters
int[] valueAsInt = new int[value.trim().length()];
for (int i = 0 ;i<value.length();i++){
valueAsInt[i]=(int)value.toCharArray()[i]-48;
}
return valueAsInt;
}
also if it's possible use shor or byte type as it's enoght to store 0,1 and you consume less memory as with int
I don't know why you want to do this, but it is a simple problem.
public static void main (String[] args) {
String s = "111232";
String element[] = s.split("");
System.out.println(element[0]);
System.out.println(element[1]);
System.out.println(element[2]);
System.out.println(element[3]);
System.out.println(element[4]);
System.out.println(element[5]);
}

Repeat String Recursively [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is homework. I get the logic but i got stuck on the code. I've done it with normally way and it takes 1 week to get the code. I need to get repeat string with recursive way in Java.
This is my code :
static String repeatString (final int n, final String[] syllables, final String currentWord) {
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
repeatString(n - 1, syllables, currentWord + syllables[i]);
}
}
return "";
}
if i call in main method like
String[] str = {"a", "b"};
repeatString(1, str, " ");
then i get output (a,b) if i change to
repeatString(2,str," ");
then i get output ( aa,ab,ba,bb) if i change to
repeatString(3,str," ");
then i get output (aaa,aab,aba,abb,baa,bab,bba,bbb) and so on.
So basically it is like 2 to the power to n. If n=1, i got 2, if n=3, i got 8, and so on.
I would be grateful if someone can help me to get this code in recursive way.
Any help is much appreciated.
The method you have there is recursive already. Being recursive does NOT mean it should have no for loops. A recursive method in cheap words means the method calls itself, which yours does.

Formula with Recursion (n+(n-1)+n) error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to use recursion to calculate how many medals a player gets for example if I enter 3 the player got 8 medals [Ex1.(3+(3-1)+3)=(3+2+3)=8]/[Ex2.(5+(5-1)+5)=(5+4+5)=14] When I enter 1 on the main method to test it works but when I change a number greater than 1 it crashes and I get red letters as error this is the error I get. I have done about 5 recursion methods already but I'm stuck on this one.
java.lang.StackOverflowError
at RecursiveFunctions.countMedals(RecursiveFunctions.java:87)
public class RecursiveFunctions{
public static int countMedals(int n){
if(n==0){
return 1+(1-1)+1;
}
else{
return countMedals((n)+(n-1)+(n));
}
public static void main(String[] args){
System.out.println("Number of Medals: " + RecursiveFunctions.countMedals(3));
}
}
Try tracing through the function to see what happens:
countMedals(3) returns countMedals(3 + 2 + 3)
countMedals(8) returns countMedals(8 + 7 + 8)
This is going to continually grow, and never hit your base case of 0.
Your formula has no recursive logic. There is no iteration, it's just a simple math equation.
public static int countMedals(int n){ return 3*n - 1;}
You recursive method has no endpoint in the recursive calls.
You call:
countMedals((n)+(n-1)+(n))
If n is 2, this expression evaluates:
countMedals((2)+(2-1)+(2)) -> countMedals(5)
And this is:
countMedals((5)+(5-1)+(5)) -> countMedals(14)
And so on... You never stop. So you stack is full, and Java crashes.
From your code, it looks like you will never reach the case where n == 0. This is why you are entering infinite recursion.
Each time you call your function with n + (n - 1) + n, which is essentially 3n - 1. So what you have is f(n) = 3n - 1, and you're passing the result of that into the function itself. Now f(n) = 0 only when n = 1 / 3. Can you see any way where n can ever be 1 / 3?
Also, try plotting this function on a graph. What do you see happening to the y values as you keep increasing x (basically n in this case)?
I don't see how you can apply recursion like this. To compute f(n) you need to compute f(3n-1), for which you need to compute f(f(3n-1)), etc. It never terminates, so you get a stack overflow.
In fact I don't know why you are recursing at all, if f(3) and f(5) both = 3n-1. Evidently you haven't understood your problem correctly.

Categories

Resources