题目地址:
https://www.lintcode.com/problem/number-complement/description
给定一个正整数 x x x,输出其补数。补数定义是将 x x x的二进制表示位按位翻转所得之数(该二进制表示不应该含前导 0 0 0,除非它自己是 0 0 0)。
可以先求一下 x x x的二进制表示的长度(去掉所有前导 0 0 0,除非它自己是 0 0 0),设长度是 l l l,则答案就是 ( 1 < < l ) − 1 − x (1<<l)-1-x (1<<l)−1−x。代码如下:
public class Solution {
/**
* @param num: an integer
* @return: the complement number
*/
public int findComplement(int num) {
// Write your code here
int len = 0, tmp = num;
while (tmp != 0) {
len++;
tmp >>= 1;
}
return (1 << len) - 1 - num;
}
}
时间复杂度 O ( log x ) O(\log x) O(logx),空间 O ( 1 ) O(1) O(1)。