Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 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