0
\$\begingroup\$

Here is my code:

package com.app;

public class Solution {

    public String toBinaryString(int n) {
        char[] buffer = new char[32];
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = '0';
        }
        int i = buffer.length - 1;
        while (n != 0) {
            if (n % 2 != 0) {
                buffer[i] = '1';
            }
            i--;
            n >>>= 1;
        }
        return new String(buffer);
    }
}

And I also wrote a few tests:

package com.app;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class SolutionTest {

    @Test
    void one() {
        Solution solution = new Solution();
        assertEquals("00000000000000000000000000000001", solution.toBinaryString(1));
    }

    @Test
    void minusOne() {
        Solution solution = new Solution();
        assertEquals("11111111111111111111111111111111", solution.toBinaryString(-1));
    }

    @Test
    void intMin() {
        Solution solution = new Solution();
        assertEquals("10000000000000000000000000000000", solution.toBinaryString(Integer.MIN_VALUE));
    }

    @Test
    void intMax() {
        Solution solution = new Solution();
        assertEquals("01111111111111111111111111111111", solution.toBinaryString(Integer.MAX_VALUE));
    }

    @Test
    void even() {
        Solution solution = new Solution();
        assertEquals("00000000000000000000000001111100", solution.toBinaryString(124));
    }

    @Test
    void odd() {
        Solution solution = new Solution();
        assertEquals("00000000000000000000000000100101", solution.toBinaryString(37));
    }
}

The problem seems to be pretty easy. However, it took me some time to make it work with negative numbers and some edge cases. So I'd greatly appreciate if you noticed any bugs in my code.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

A single loop would be preferable.

public static String toBinaryString(int n) {
    char[] buffer = new char[32];
    for (int i = buffer.length - 1; i >= 0; i--) {
        buffer[i] = '0' + (n & 1);
        n >>>= 1;
    }
    return new String(buffer);
}
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.