본문 바로가기
Algorithm/LeetCode

💯 Daily LeetCode Challenge Day_05 - Hamming Distance

by HaningYa 2020. 7. 6.
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


문제

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4
Output: 2
Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.


Swift 는 String(x, radix: 2) 로 진수 변환을 할 수 있다.

2진수로 바꿔준 뒤 pad 함수를 이용하여 String 길이가 긴 이진수에 맞춰 0문자를 넣어줘 문자열 길이를 같게 만든다.

그리고 문자가 다르면 answer += 1 하며 정답을 찾는다.

class Solution {
    func hammingDistance(_ x: Int, _ y: Int) -> Int {
        //decimal to binary
        var binX = String(x, radix: 2)
        var binY = String(y, radix: 2)
        //make same digit
        if binX.count > binY.count{
            binY = pad(binY, binX.count)
        }else{
            binX = pad(binX,binY.count)
        }
        //compare
        var answer = 0
        for i in 0..<binX.count{
            let index = binX.index(binX.startIndex, offsetBy: i)
            if binX[index] != binY[index] {
                answer += 1
            }
        }
        
        return answer
    }
    func pad(_ string : String,_ toSize: Int) -> String {
        var padded = string
        for _ in 0..<(toSize - string.count) {
            padded = "0" + padded
        }
        return padded
    }
}
728x90

댓글