LeetCode - 67. Add Binary(Math, String, Bit Manipulation, Simulation)*

YAMAMAMO·2022년 11월 8일
0

LeetCode

목록 보기
80/100

문제

Given two binary strings a and b, return their sum as a binary string.

https://leetcode.com/problems/add-binary/description/

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

풀이


class Solution {
    public String addBinary(String a, String b) {
        StringBuilder res = new StringBuilder();
        int i = a.length()-1;
        int j = b.length()-1;
        boolean carry=false;

        while(i>-1||j>-1){
            char aC = (i>-1)?a.charAt(i--):'0';
            char bC = (j>-1)?b.charAt(j--):'0';

            if(aC=='1'&&bC=='1'){
                res = (carry) ? res.append('1') : res.append('0');
                carry = true;
            }else if(aC=='0'&&bC=='0'){
                res = (carry)?res.append('1'):res.append('0');
                carry = false;
            }else{
                res = (carry)?res.append('0'):res.append('1');
            }
        }
        
         if(carry) res.append('1');

         return res.reverse().toString();
    }
}
profile
안드로이드 개발자

0개의 댓글