728x90
문제
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
'Algorithm > LeetCode' 카테고리의 다른 글
💯 Daily LeetCode Challenge Day_07 - Island Perimeter (0) | 2020.07.07 |
---|---|
💯 Daily LeetCode Challenge Day_06 - Plus One (0) | 2020.07.07 |
💯 Daily LeetCode Challenge Day_04 - Ugly Number II (0) | 2020.07.06 |
💯 Daily LeetCode Challenge Day_03 - Prison Cells After N Days (0) | 2020.07.03 |
💯 Daily LeetCode Challenge Day_02 - Binary Tree Level Order Traversal II (0) | 2020.07.03 |
댓글