Java Solution needs improvement for unrealistic String arguments.


  • 0
    M
    public String addBinary(String a, String b) {
            int first = Integer.parseInt(a);
            for (int i=0; i<first; i++) {
                if (Integer.toBinaryString(i).equals(a)) {
                    first = i;
                    break;
                }
            }
            int second = Integer.parseInt(b);
            for (int i=0; i<second; i++) {
                if (Integer.toBinaryString(i).equals(b)) {
                    second = i;
                    break;
                }
            }
            int finalNumber = first + second;
            return Integer.toBinaryString(finalNumber);
        }

  • 0
    M

    This won't work because integer has a fixed number of bits. So, if input string a or b has a length that is bigger than the size of int, then the parseInt method will fail.

    The better way is to use arithmetic. e.g. 1 + 1 = 0 and carry over = 1


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.