龙熠的技术小站

Leetcode 476 Number Complement

给一个数字,找到二进制对应的数字,例如5(101)对应是2(10)


题目

1
2
3
4
5
6
7
8
描述
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.
1
2
3
4
5
6
7
8
9
例子
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

解题思路

先找出传入的数字的长度

然后再按位确定是否要转换并相加

解题

Language : swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
func findComplement(_ num: Int) -> Int {
var re = 0
var a = num
var b = num
var length : Int = 0
while b > 0 {
length += 1
b = b / 2
}
for i in 1...length {
re += ((a % 2 > 0) ? 0 : (1<<(i-1)))
a = a / 2
}
return re
}
}
分享