LeetCode-Java-476. Number Complement
原创
©著作权归作者所有:来自51CTO博客作者MC43700000046E4的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目
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.
Example 1:
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.
Example 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.
代码
先用栈存储其二进制最后转换即可,也可用Integer内置方法装换
class Solution {
public int findComplement(int num) {
int sum = 0;
LinkedList<Integer> integers = new LinkedList<>();
while(num!=0){
int temp=num%2;
integers.push(temp);
num>>>=1;
}
Iterator<Integer> iterator = integers.iterator();
while (iterator.hasNext()){
Integer next = iterator.next();
if(next==0)
{
sum = sum*2+1;
}else{
sum*=2;
}
}
return sum;
}
}