728x90
문제
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Constraints:
- Each string consists only of '0' or '1' characters.
- 1 <= a.length, b.length <= 10^4
- Each string is either "0" or doesn't contain any leading zero.
Swift 에서 제공하는 radix 를 이용하면 decimal -> binary, binary -> decimal 바꿀 수 있다.
class Solution {
func addBinary(_ a: String, _ b: String) -> String {
let number_a = Int(a,radix:2)
let number_b = Int(b,radix:2)
let sum = number_a! + number_b!
return String(sum, radix:2)
}
}
그러나 이 문제는 일일히 계산해라는 거기 때문에
분명히 String 인 것도 Int 범위를 벗어나는 계산을 시킬꺼기 때문에
이렇게 하면 안된다.
class Solution {
func addBinary(_ a: String, _ b: String) -> String {
var maxNum = b
var minNum = a
if a.count > b.count {
maxNum = a
minNum = b
}
let diff = maxNum.count - minNum.count
for i in 0..<diff {
minNum = ("0\(minNum)")
}
var answer = ""
var digit = 0
var carry = 0
for i in (0..<maxNum.count).reversed(){
let index = maxNum.index(maxNum.startIndex, offsetBy: i)
let num1 = minNum[index].wholeNumberValue!
let num2 = maxNum[index].wholeNumberValue!
let sum = num1 + num2 + carry
carry = sum/2
digit = sum%2
answer = "\(digit)\(answer)"
}
if carry != 0 {
answer = "\(carry)\(answer)"
}
return answer
}
}
728x90
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode - Detect Capital (0) | 2020.08.07 |
---|---|
💯 Daily LeetCode Challenge Day_20 - Remove Linked List Elements (2) | 2020.07.29 |
💯 Daily LeetCode Challenge Day_18 - Course Schedule 2 (0) | 2020.07.24 |
💯 Daily LeetCode Challenge Day_17 - Top K Frequent Elements (0) | 2020.07.18 |
💯 Daily LeetCode Challenge Day_16 - Pow(x, n) (0) | 2020.07.18 |
댓글