finishing

1, & : bit logic and. 1&1 is 1, and the rest is 0

2, | : a logical or. 1, 1 or 1, 0 is 1, 0 is 0

3, ^ : bit logic xor: different from 1, that is, 1 ^ 0 0 is 1, 1 ^ 1 or 0 ^ 0 is 0.

4, ~ : bit logic reverse: ~ 1 is 0, ~ 0 is 1.

5, >> : right shift 6, << : left shift

A, add

A +b = a^b + a&b << 1

Example of adding without carrying:

For example, 4 + 5 0000 0100 0000 0100 0000 0100 ^ 0000 0101 + 0000 0101 + 0000 0101 (add but not carry) ------------- ------------- ------------- 0000 0001 0000 1001 0000 0001Copy the code

& : bit logic and. 1&1 is 1, and the rest is 0

A&b to the left is the carry of a bit operation

Second, the subtraction

Subtraction is addition. 5-4 => 5 + (-4), which can also be added, but we need to pay attention to what binary value -4 is stored in the computer, so we can calculate 5 + (-4).

The original, inverse, and complement of positive numbers are the same

The source code of a negative number, with the highest bit 1

The inverse of negative numbers: the sign bit remains unchanged, the remaining 0,1 is reversed

The complement for negative numbers: the inverse + 1 is 1111 1100

The value a computer stores is always the complement of a number

Third, the multiplication

Multiplication can be thought of as multiple addition computations, such as 5 * 4, which can be computed as 5 + 5 + 5 + 5 with only one loop.

Fourth, the division

If you can divide everything, it’s actually subtraction, so 36/9, how many times can you subtract 9 from 36. So you can calculate the number of subtractions based on 36 minus 9. Division may have decimals, which involves the calculation and storage of floating point numbers. The situation is more complicated and will not be discussed too much.

Original: www.cnblogs.com/k5210202/p/…

Leetcode

Question 1

In the array, only one number appears once, and the rest appear twice. Find the number that appears once

Xor supports commutative and associative laws.

1 ^ 2 ^ 3 ^ ^ 4 5 ^ 1 ^ 2 ^ 3 ^ 4 = ^ ^ 1 (1) (2 ^ 2) ^ ^ (3 ^ 3) (4 ^ 4) 5 = 0 ^ ^ ^ ^ ^ 0 0 0 5 = 5.Copy the code

Question 2

Determine whether a positive integer n is a power of 2

Important: If a number is a power of 2, it means that in the binary representation of n, only one bit is a 1, and all the others are zeros.

Rule:

n = n & (n - 1)
Copy the code

So I can get rid of the 1 on the left and right side of n, so:

n & (n - 1) == 0; If it's zero, you can tell if it's a power of two.Copy the code

Question 3

How many bits do I need to change to convert the integer n to m?

T = n&m tells you how many different bits there are in binaryCopy the code

You just have to figure out how many 1’s there are in the binary bits of T.

Reference article: juejin.cn/post/684490…

If you find this article inspiring, in order to reach more people, it’s ok

Like it and make it available to more people