Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Counting
- 코테
- Stack
- Matrix
- hash table
- 자바
- array
- Binary Search
- SQL
- Method
- bit manipulation
- simulation
- Class
- dynamic programming
- implement
- greedy
- Binary Tree
- two pointers
- Tree
- geometry
- 파이썬
- database
- Number Theory
- string
- sorting
- Math
- java
- 코딩테스트
- 구현
- Data Structure
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Easy] 67. Add Binary 본문
1. Input
1) String a
2) String b
2. Output
1) 2진수를 담은 문자열 a,b의 합을 2진수 문자열로 반환
3. Constraint
1) 1 <= a.length, b.length <= 10^4
2) a와 b는 0과 1로만 이루어져 있다.
3) a와 b는 0이 아닌 2진수이다.
4. Example
Input: a = "1010", b = "1011" -> Output: "10101"
5. Code
1) 첫 코드(2023/05/09)
class Solution {
public String addBinary(String a, String b) {
Stack<Integer> st = new Stack<>();
int carry = 0, ai = a.length()-1, bi = b.length()-1;
while(ai>=0 || bi>=0){
int sum = carry;
if(ai>=0)
sum += a.charAt(ai--)=='1' ? 1 : 0;
if(bi>=0)
sum += b.charAt(bi--)=='1' ? 1 : 0;
carry = sum/2;
st.push(sum%2);
}
if(carry==1)
st.push(1);
StringBuilder sb = new StringBuilder();
while(!st.empty())
sb.append(st.pop());
return sb.toString();
}
}
- 스택을 이용하지 않고 바로 append를 한 다음, sb.reverse().toString()으로 반환해도 된다.
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[LeetCode/Easy] 94. Binary Tree Inorder Traversal (0) | 2023.05.09 |
---|---|
[LeetCode/Easy] 70. Climbing Stairs (0) | 2023.05.09 |
[프로그래머스/Lv.1] 공원 산책 (0) | 2023.05.09 |
[프로그래머스/Lv.1] 추억 점수 (0) | 2023.05.08 |
[LeetCode/Easy] 2670. Find the Distinct Difference Array (0) | 2023.05.08 |