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);
}
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.