Computation of binary representation of an integer
  • Posted: 5 years ago
  • Edit
  • answers (1)
  • views (1321)

Suppose you are given a non - negative integer. What will be the recursive function to compute the binary of it?


Posted Answers



  • If the given integer is 0 , return 0 .
  • If the given integer is 1 , return 1 .
  • If the given integer in even, recursively find half of the integer and pad it with 0 in each iteration.
  • If the given integer in odd, recursively find half of the integer and pad it with 1 in each iteration.

Example -


public static string decimal2Binary(int n){

if(n == 0)
return "0";
if(n == 1)
return "1";
/* When n is even */
if(n%2 == 0)
return decimal2Binary(n/2) + "0";
/* When n is odd */
else
return decimal2Binary(n/2) + "1";
}

You need to Sign In to post your solution.