Step-by-Step

[Java] Daily LeetCode Challenge 67. Add Binary 본문

언어/JAVA

[Java] Daily LeetCode Challenge 67. Add Binary

희주(KHJ) 2023. 2. 14. 20:06

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

 

Add Binary - LeetCode

Can you solve this real interview question? Add Binary - Given two binary strings a and b, return their sum as a binary string.   Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101"   Constraints: *

leetcode.com

 

2진수 ↔ 10진수 (Binary to Decimal / Decimal to Binary) 방법은 쓰지말자 범위를 보면 오버플로우 됨

 

carry 사용해서 값을 넘겨주고, StringBuilder 이용해서 값을 그때그때 더해주면 됨

분명 더 짧은 방법이 있을테지만..! 통과한거보니 방법이 틀리진 않은듯!

 

 

[코드]

import java.util.*;
class Solution {
    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();

        a = "0"+a;
        b = "0"+b;
        
        int aIdx = a.length()-1, bIdx = b.length()-1;

        int carry = 0;
        while(aIdx != 0 || bIdx != 0){
            int anum = a.charAt(aIdx)-'0';
            int bnum = b.charAt(bIdx)-'0';

            int sum = carry + anum + bnum;

            if(sum > 1){
                carry = 1;
                sum -= 2;
                sb.append(sum + "");
            }else {
                carry = 0;
                sb.append(sum + "");
            }

            if(aIdx != 0)
                aIdx--;
            if(bIdx != 0)
                bIdx--;
        }

        if(carry == 1)
            sb.append("1");
        
        return sb.reverse().toString();
    }
}
Comments