Family Day update
This commit is contained in:
parent
aac6731f2c
commit
9ad63ea473
2442 changed files with 39761 additions and 8255 deletions
22
Task/Gray-code/Swift/gray-code.swift
Normal file
22
Task/Gray-code/Swift/gray-code.swift
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
func grayEncode(_ i: Int) -> Int {
|
||||
return (i >> 1) ^ i
|
||||
}
|
||||
|
||||
func grayDecode(_ i: Int) -> Int {
|
||||
switch i {
|
||||
case 0:
|
||||
return 0
|
||||
case _:
|
||||
return i ^ grayDecode(i >> 1)
|
||||
}
|
||||
}
|
||||
|
||||
for i in 0..<32 {
|
||||
let iStr = String(i, radix: 2)
|
||||
let encode = grayEncode(i)
|
||||
let encodeStr = String(encode, radix: 2)
|
||||
let decode = grayDecode(encode)
|
||||
let decodeStr = String(decode, radix: 2)
|
||||
|
||||
print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))")
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue