[LeetCode] Add Binary

아르당·2025년 2월 24일
0

LeetCode

목록 보기
14/60
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 개의 이진 문자열 a와 b가 주어지고, 그 문자열의 합을 이진 문자열로 반환해라.

Example

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

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

Constraints

  • 1 <= a.length, b.length <= 10^4
  • a와 b는 오직 '0'과 '1'로 되어있다.
  • 각 문자열은 0을 제외하고 제일 앞에 0이 오지 않는다.

All Code

class Solution {
    public String addBinary(String a, String b) {
        int i = a.length() - 1;
        int j = b.length() - 1;
        int temp = 0;
        StringBuilder sb = new StringBuilder();

        while(i >= 0 || j >= 0 || temp > 0){
            if(i >= 0){
                temp = temp + a.charAt(i) - '0';
                i--;
            }

            if(j >= 0){
                temp = temp + b.charAt(j) - '0';
                j--;
            }

            sb.append(temp % 2);
            temp = temp / 2;
        }

        return sb.reverse().toString();
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글