• 문제 링크
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
• 풀이 코드
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) sum += a.charAt(i--) - '0';
if (j >= 0) sum += b.charAt(j--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
return carry != 0 ? sb.append(carry).reverse().toString() : sb.reverse().toString();
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 69. Sqrt(x) - Java (0) | 2026.05.22 |
|---|---|
| [LeetCode] 66. Plus One - Java (0) | 2026.05.20 |
| [LeetCode] 58. Length of Last Word - Java (0) | 2026.05.19 |
| [LeetCode] 35. Search Insert Position - Java (0) | 2026.05.18 |
| [LeetCode] 24. Swap Nodes in Pairs - Java (0) | 2026.05.17 |
댓글