[코테 풀이] Add Binary

시내·2024년 6월 4일

Q_67) Add Binary

출처 : https://leetcode.com/problems/add-binary/
Given two binary strings a and b, return their sum as a binary string.

class Solution {
    public String addBinary(String a, String b) {
         String result = "";
        boolean carry = false;
        if (a.length() < b.length()) { //a is always longer
            String c = a;
            a = b;
            b = c;
        }
        int lengthA = a.length();
        int lengthB = b.length();
        for (int z = 0; z < lengthA - lengthB; z++) {
            b = "0" + b;
        }
        for (int i = lengthA - 1; i >= 0; i--) {
            if (a.charAt(i) - 48 + b.charAt(i) - 48 >= 2) {
                if (carry) {
                    if (i == 0) {
                        result = "11" + result;
                    } else {
                        result = "1" + result;
                    }
                } else {
                    if (i == 0) {
                        result = "10" + result;
                    } else {
                        result = "0" + result;
                    }
                }
                carry = true;
            } else if (a.charAt(i) - 48 + b.charAt(i) - 48 == 1) {
                if (carry) {
                    if (i == 0) {
                        result = "10" + result;
                    } else {
                        carry = true;
                        result = "0" + result;
                    }
                } else {
                    carry = false;
                    result = "1" + result;
                }
            } else if (a.charAt(i) - 48 + b.charAt(i) - 48 == 0) {
                if (carry) {
                    result = "1" + result;
                } else {
                    result = "0" + result;
                }
                carry = false;
            }
        }

        int count = 0;
        if (result.startsWith("0") && result.length() >= 2) {
            while (result.charAt(count) == '0') {
                count++;
            }
            result = result.substring(count);
        }
        return result;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글