Showing posts with label Bit Manipulation. Show all posts
Showing posts with label Bit Manipulation. Show all posts

Friday, January 18, 2019

怎么理解Two's complement

在Java里整数的表示就用的是Two's complement

转换方法:一个整数n, 想要得到-n的二进制表示,则可将n的二进制写出来,然后挨个翻转,完成后加1即可。比如 8 -> 00001000 -> 11110111 -> 11111000 -> -8

如此来算,则
00000001 ->1, 00000010 -> 2, ... , 01111111 -> 127
11111111 -> -1, 11111110 -> -2, ... , 10000001 -> -127, 10000000 -> -128

也可以这么想,n和-n加起来就是00000000 (往更高一位进一个1,100000000)

好处:加减都可以换成加法了。12-60 = 12 + (-60)

数学上怎么理解:
-n就是0 - n,然后0我们可以想像成100000000, 11111111-n就是把n 挨个翻转,但是11111111还比“0“多减了个1,所以我们要把结果加1. (就是减法上借位的思想)。


Wednesday, February 24, 2016

Bit Manipulation

Bit Manipulation

常用operators:
~        unary bitwise complement operator, inverts a bit pattern
<<       signed left shift operator
>>       signed right shift operator
>>>     unsigned right shift operator, a zero into the leftmost position
&        bitwise AND
^         bitwise exclusive OR   (必须有且只有一个为真才行)
|          bitwise inclusive OR

特性:
(n&(n-1) == 0) true if n is power of 2. (or if n=1)
  n^n = 0
可以用来判断两个词有没有重复字符

常见问题:
Leetcode 136 - Single Number
Leetcode 268 - Missing Number
Leetcode 318 - Maximum Product of Word Lengths