Advertisement
Guest User

Recursion

a guest
Apr 24th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. public class Binary {
  2.  
  3. public static void main(String[] args) {
  4. StringBuilder binary = new StringBuilder();
  5. binaryCount(777,binary);
  6. // binary.append('a');
  7. // binary.insert(0, 'w');
  8. // binary.insert(2, 'l');
  9. System.out.println(binary);
  10.  
  11. }
  12.  
  13. static StringBuilder binaryCount(int n, StringBuilder binary){
  14. //Base Case: if n=1 append a 1 to the stringbuilder for
  15. //the binary representation of the digital number
  16. if(n==1){
  17. binaryBuilder(false, binary);
  18. return binary;
  19. }
  20. //divide n by 2 and that becomes the new n
  21. //mod n by 2 and that becomes the test number for even or odd to add
  22. //the 0 or 1 to the binary representation of the digital number
  23. else{
  24. int test = n%2;
  25. //if test is even pass the binary builder method a true
  26. //if test is odd pass the binary builder method a false
  27. if(test%2==0){
  28. binaryBuilder(true, binary);
  29. }
  30. else{
  31. binaryBuilder(false, binary);
  32. }
  33. return binaryCount(n/2, binary);
  34. }
  35. }
  36.  
  37. static StringBuilder binaryBuilder(boolean tf,StringBuilder binary){
  38. //if tf is true, add a 0 to index 0
  39. if(tf){
  40. binary.insert(0, 0);
  41. }
  42. //if tf is false add a 1 to index 0
  43. else{
  44. binary.insert(0, 1);
  45. }
  46. return binary;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement