在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Every non-negative integer The complement of a binary representation is the number in binary you get when changing every For a given number Example 1: Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2: Input: 7
Output: 0
Example 3: Input: 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Note:
每个非负整数 二进制的补码表示是将每个 给定十进制数 示例 1: 输入:5 输出:2 解释:5 的二进制表示为 "101",其二进制补码为 "010",也就是十进制中的 2 。 示例 2: 输入:7 输出:0 解释:7 的二进制表示为 "111",其二进制补码为 "000",也就是十进制中的 0 。 示例 3: 输入:10 输出:5 解释:10 的二进制表示为 "1010",其二进制补码为 "0101",也就是十进制中的 5 。 提示:
Runtime: 4 ms
Memory Usage: 19 MB
1 class Solution { 2 func bitwiseComplement(_ N: Int) -> Int { 3 var N = N 4 var bits:[Int] = [Int]() 5 repeat{ 6 bits.append(N % 2) 7 N /= 2 8 }while(N != 0) 9 for i in 0..<bits.count 10 { 11 bits[i] = 1 - bits[i] 12 } 13 var val:Int = 0 14 var p:Int = 1 15 for i in 0..<bits.count 16 { 17 val += p * bits[i] 18 p *= 2 19 } 20 return val 21 } 22 } 4ms
1 class Solution { 2 func bitwiseComplement(_ N: Int) -> Int { 3 var c = 1 4 while c < N { 5 c = (c << 1) | 1 6 } 7 return N ^ c 8 } 9 } Runtime: 8 ms Memory Usage: 18.9 MB
1 class Solution { 2 func bitwiseComplement(_ N: Int) -> Int { 3 var arrInt:[Int] = String(N,radix:2).map{Int(String($0))!} 4 for i in 0..<arrInt.count 5 { 6 arrInt[i] = 1 - arrInt[i] 7 } 8 return String(arrInt.map{Character(String($0))}).BinaryToDecimal() 9 } 10 } 11 extension String{ 12 func BinaryToDecimal() -> Int { 13 var sum:Int = 0 14 for c in self.characters { 15 if let number = Int(String(c)) 16 { 17 sum = sum * 2 + number 18 } 19 } 20 return sum 21 } 22 }
|
请发表评论