본문 바로가기
Algorithm/LeetCode

💯 Daily LeetCode Challenge Day_19 - Add Binary

by HaningYa 2020. 7. 29.
728x90

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

 


문제

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

댓글