Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 비밀 지도 #58

Closed
hwangJi-dev opened this issue Jan 6, 2023 · 0 comments
Closed

[Algorithm] 비밀 지도 #58

hwangJi-dev opened this issue Jan 6, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Jan 6, 2023

💬 문제

[코딩테스트 연습 - [1차] 비밀지도](https://school.programmers.co.kr/learn/courses/30/lessons/17681)


💬 풀이

func solution(_ n:Int, _ arr1:[Int], _ arr2:[Int]) -> [String] {
    var answer: [String] = []
    var map: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: n)
    
    for (index, i) in arr1.enumerated() {
        var radix1 = String(i, radix: 2)
        var radix2 = String(arr2[index], radix: 2)
        
        if radix1.count < n {
            while radix1.count < n {
                radix1.insert("0", at: radix1.startIndex)
            }
        }
        
        if radix2.count < n {
            while radix2.count < n {
                radix2.insert("0", at: radix2.startIndex)
            }
        }
        
        for (idx, j) in radix1.enumerated() {
            if j == "1" || Array(radix2)[idx] == "1" {
                map[index][idx] = 1
            }
        }
    }
    
    for m in map {
        var str = ""
        for k in m {
            str += k == 0 ? " " : "#"
        }
        answer.append(str)
    }
    
    return answer
}

💬 더 나은 방법?

// 더 나은 풀이
func solution(_ n:Int, _ arr1:[Int], _ arr2:[Int]) -> [String] {
    return (0..<n).map {
        // | : 비트 OR 연산자
        let binary = String(arr1[$0] | arr2[$0], radix: 2)
        let padded = String(repeating: "0", count: n - binary.count) + binary
        return padded.reduce("") { $0 + ($1 == "0" ? " " : "#") }
    }
}

💬 알게된 문법

[Swift 고급 연산자 - 비트 연산자]

✅ NOT

비트 NOT 연산자는 모든 비트 수를 거꾸로 한다.

연산자: ~

  • 00001111 → 11110000

✅ AND

비트 AND 연산자는 두 수의 비트를 AND 연산으로 결합한다. ( 두 수가 모두 1일경우 1 )

연산자: &

  • 11111100 & 00111100 → 00111100

✅ OR

비트 OR 연산자는 두 수의 비트를 OR 연산한다. ( 두 수중 하나라도 1일경우 1 )

연산자: |

  • 10110010 | 01011110 → 11111110

✅ XOR

비트 XOR 연산자는 배타적인 OR 연산자로, 두 값을 XOR 연산한다. ( 두 수중 하나만 1일경우 1 )

연산자: ^

  • 00010100 ^ 00000101 → 00010001

출처:

[[Swift]Advanced Operators 정리](http://minsone.github.io/mac/ios/swift-advanced-operators-summary)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant