I am unable to understand this why it prints the total binary bits instead of last bit in Java and C++.I checked it in C it present as I think i.e only last bit. However, in C++and java it prints all bits.
public static void main(String[] args) {
toBin(2);
}// end of main
static void toBin(int b) {
int modu = 0;
if (b < 1) {
return;
}
modu = b % 2;
b=(b>>1);
toBin(b);
System.out.print(modu);
}// end of toBin()
The way toBin() works is that it first finds the remainer when divided by two
adds that to the beginning, then divides by 2
and repeats recursively until there’s nothing left.
If you think about it in terms of decimal, it’s a little easier.
Say you have the number 4863, and you want to print it out in base 10.
First you take n % 10 which is 3, then you divide by 10, and you 486. Repeat, you have 6 and 48, and so.
The reason print is after toBin(b) is so it doesn’t need to maintain a string. Instead, it’ll print the most inner recursive call first, and as it exits out, it’ll print the remaining ones in reverse.
Essentially, the following (which is probably easier to understand) does the same, but prints the digits backwards: