Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Binary {
- public static void main(String[] args) {
- StringBuilder binary = new StringBuilder();
- binaryCount(777,binary);
- // binary.append('a');
- // binary.insert(0, 'w');
- // binary.insert(2, 'l');
- System.out.println(binary);
- }
- static StringBuilder binaryCount(int n, StringBuilder binary){
- //Base Case: if n=1 append a 1 to the stringbuilder for
- //the binary representation of the digital number
- if(n==1){
- binaryBuilder(false, binary);
- return binary;
- }
- //divide n by 2 and that becomes the new n
- //mod n by 2 and that becomes the test number for even or odd to add
- //the 0 or 1 to the binary representation of the digital number
- else{
- int test = n%2;
- //if test is even pass the binary builder method a true
- //if test is odd pass the binary builder method a false
- if(test%2==0){
- binaryBuilder(true, binary);
- }
- else{
- binaryBuilder(false, binary);
- }
- return binaryCount(n/2, binary);
- }
- }
- static StringBuilder binaryBuilder(boolean tf,StringBuilder binary){
- //if tf is true, add a 0 to index 0
- if(tf){
- binary.insert(0, 0);
- }
- //if tf is false add a 1 to index 0
- else{
- binary.insert(0, 1);
- }
- return binary;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement