在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. Example 1: Input: 2
Output:
Example 2: Input: 0
Output:
格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。 示例 1: 输入: 2 输出: 示例 2: 输入: 0 输出: 8ms 1 class Solution { 2 func grayCode(_ n: Int) -> [Int] { 3 var result = [Int]() 4 var i: Int = 0 5 while i < (1 << n) { 6 result.append( i ^ (i >> 1)) 7 i += 1 8 } 9 return result 10 } 11 } 8ms 1 class Solution { 2 func grayCode(_ n: Int) -> [Int] { 3 var result = [Int]() 4 for i in 0..<1 << n { 5 result.append((i >> 1) ^ i) 6 } 7 return result 8 } 9 } 12ms 1 class Solution { 2 func grayCode(_ number: Int) -> [Int] { 3 guard number > 0 else { 4 return [0] 5 } 6 var result: [Int] = [0, 1] 7 for idx in 1..<number { 8 for iidx in (0...result.count - 1).reversed() { 9 result.append(result[iidx] + 1 << idx) 10 } 11 } 12 return result 13 } 14 } 16ms 1 class Solution { 2 func grayCode(_ n: Int) -> [Int] { 3 if n == 0 { 4 return [0] 5 } 6 7 if n == 1 { 8 return [0, 1] 9 } 10 11 var res = [0, 1] 12 13 for i in 1..<n { 14 var result: [Int] = [] 15 for val in res.reversed() { 16 result.append(val + (1<<i)) 17 } 18 res = res + result 19 } 20 21 return res 22 } 23 } 24ms 1 class Solution { 2 func grayCode(_ n: Int) -> [Int] { 3 if n == 0 { 4 return [0] 5 } 6 var result = [Array<Int>(repeating: 0, count: n)]; 7 for i in 0 ..< n { 8 let count = result.count 9 for j in stride(from: count - 1, to: -1, by: -1) { 10 var temp = result[j] 11 temp[n - i - 1] = 1 12 result.append(temp) 13 } 14 } 15 var realResult = Array<Int>() 16 for tempArr in result { 17 realResult.append(binTodec(number: tempArr)) 18 } 19 return realResult 20 } 21 22 func binTodec(number num: Array<Int>) -> Int { 23 var sum: Int = 0 24 for c in num { 25 sum = sum * 2 + c 26 } 27 return sum 28 } 29 }
|
请发表评论