forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path461_Hamming_Distance.swift
executable file
·41 lines (32 loc) · 1.14 KB
/
461_Hamming_Distance.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import Foundation
//: Problem Link: https://leetcode.com/problems/hamming-distance/
class Solution_461 {
func hammingDistance(_ x: Int, _ y: Int) -> Int {
var hammingDistance: Int = 0
var maxLen = 0
var strX = String(x, radix: 2)
var strY = String(y, radix: 2)
if strX.characters.count > strY.characters.count {
maxLen = strX.characters.count
strY = self.pad(string: strY, toSize: maxLen)
} else {
maxLen = strY.characters.count
strX = self.pad(string: strX, toSize: maxLen)
}
for index in 0..<maxLen {
let a = strX[strX.index(strX.startIndex, offsetBy: index)]
let b = strY[strY.index(strY.startIndex, offsetBy: index)]
if a != b {
hammingDistance += 1
}
}
return hammingDistance;
}
func pad(string : String, toSize: Int) -> String {
var padded = string
for _ in 0..<(toSize - string.characters.count) {
padded = "0" + padded
}
return padded
}
}