★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-zvhiaada-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Every non-negative integer N
has a binary representation. For example, 5
can be represented as "101"
in binary, 11
as "1011"
in binary, and so on. Note that except for N = 0
, there are no leading zeroes in any binary representation.git
The complement of a binary representation is the number in binary you get when changing every 1
to a 0
and 0
to a 1
. For example, the complement of "101"
in binary is "010"
in binary.github
For a given number N
in base-10, return the complement of it's binary representation as a base-10 integer.微信
Example 1:app
Input: 5
Output: 2 Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:spa
Input: 7
Output: 0 Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:code
Input: 10
Output: 5 Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Note:htm
0 <= N < 10^9
每一個非負整數 N
都有其二進制表示。例如, 5
能夠被表示爲二進制 "101"
,11
能夠用二進制 "1011"
表示,依此類推。注意,除 N = 0
外,任何二進制表示中都不含前導零。blog
二進制的補碼錶示是將每一個 1
改成 0
且每一個 0
變爲 1
。例如,二進制數 "101"
的二進制補碼爲 "010"
。ci
給定十進制數 N
,返回其二進制表示的補碼所對應的十進制整數。
示例 1:
輸入:5 輸出:2 解釋:5 的二進制表示爲 "101",其二進制補碼爲 "010",也就是十進制中的 2 。
示例 2:
輸入:7 輸出:0 解釋:7 的二進制表示爲 "111",其二進制補碼爲 "000",也就是十進制中的 0 。
示例 3:
輸入:10 輸出:5 解釋:10 的二進制表示爲 "1010",其二進制補碼爲 "0101",也就是十進制中的 5 。
提示:
0 <= N < 10^9
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 }
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
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 }