Skip to content

[Algorithm] 비밀 지도 #58

Description

@hwangJi-dev

💬 문제

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


💬 풀이

func solution(_ n:Int, _ arr1:[Int], _ arr2:[Int])->[String]{varanswer:[String]=[]varmap:[[Int]]=Array(repeating:Array(repeating:0, count: n), count: n)for(index, i)in arr1.enumerated(){varradix1=String(i, radix:2)varradix2=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}}}formin map {varstr=""forkin m {
str += k ==0?"":"#"}
answer.append(str)}return answer
}

💬 더 나은 방법?

// 더 나은 풀이
func solution(_ n:Int, _ arr1:[Int], _ arr2:[Int])->[String]{return(0..<n).map{
// | : 비트 OR 연산자
letbinary=String(arr1[$0] | arr2[$0], radix:2)letpadded=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)

Activity

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

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions