1012. Complement of Base 10 Integer

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)

Integer类中的numberOfLeadingZeros(int i) 解析

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值