Step-by-Step
[Java] Daily LeetCode Challenge 67. Add Binary 본문
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();
}
}
'언어 > JAVA' 카테고리의 다른 글
[Java] LeetCode 395. Longest Substring with At Least K Repeating Characters (0) | 2023.02.17 |
---|---|
[Java] Daily LeetCode Challenge 783. Minimum Distance Between BST Nodes (0) | 2023.02.17 |
[Java] Daily LeetCode Challenge 2306. Naming a Company (0) | 2023.02.09 |
[Java] Daily LeetCode Challenge 904. Fruit Into Baskets (0) | 2023.02.07 |
[Java] 백준 14908 - 구두 수선공 (0) | 2023.01.31 |
Comments