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.
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.
For a given number N in base-10, return the complement of it’s binary representation as a base-10 integer.
今天这道题,LeetCode给出的是easy,我竟然做出来了!虽然是简单题,但我依旧很高兴
输入的N是不确定的,所以用了list集合存储,十进制转化为二进制,通过对2取余本来是倒叙放入集合当中的,没想到倒叙却帮了忙,在集合中的索引是n,那就是2的n次幂。
看了别人提交的答案,跪了,别人一行就完事了。。。
Just actually do the complement operation ~, after first shifting away all the leading zeroes, and then shift away all the trailing ones.(实际上就是做补码运算,先移走所有的前导零,然后再移走所有的后置零。)
public int bitwiseComplement(int N) {
return (N==0) ? 1 : (~(N<<(N=Integer.numberOfLeadingZeros(N))))>>N;
}
Integer.numberOfLeadingZeros(N)的用法:
Integer.numberOfLeadingZeros(int i)