complement_of_base_10_integer

Question:

complement_of_base_10_integer

Solution:

1
2
3
4
public int bitwiseComplement(int N) {
if(N == 0) return 1;
return (Integer.highestOneBit(N)<<1) - N -1;
}

eg:
N=10, ans = 5 = 16 - 10 - 1
N=7, ans = 0 = 8 - 7 -1
N=5, ans = 2 = 6 -5 -1

Analyze:

N = 10, binaryN 1010
ans = 5,binaryA 0101
binaryN + binaryA = 1111
binaryN + binaryA + 1= 10000
so, binaryA = 10000 - binaryN - 1

Powered by KyleCe

Copyright © 2015 - 2019 KyleCe All Rights Reserved.

访客数 : | 访问量 :