The beauty of programming-the charm of numbers

Source: Internet
Author: User
Tags array sort

1. The number of 1 in the binary of integer V

[Cpp]
Int Count (int v)
{
Int num = 0;
While (v)
{
Num + = v & 0x01;
V >>> = 1;
}
Return num;
}
 
Int Count (int v)
{
Int num = 0;
While (v)
{
V & = (v-1 );
Num ++;
}
Return num;
}
How many digits are different in the binary representation of integers A and B?
Returns two integers, A and B, and returns the number of 1.
[Cpp]
Int Count (int a, int B)
{
Int num = 0;
Int v = a ^ B;
While (v)
{
V & = (v-1 );
Num ++;
}
Return num;
}
Integer n to determine whether it is the power of 2 (that is, there is only one 1 in the binary)
Answer: n> 0 & (n & (n-1) = 0)
Principle:
Because the number of n 2 binary represents 1st bits for 1, the rest is 0, and the X-1 (if x is the n 2) the binary representation of the obtained number is exactly 1st bits and the rest is 1. The two are the same, and the result is 0. Otherwise, the result is certainly not 0.


2. There are several zeros at the end of the factorial of N.
If N! = K * 10 m, and K cannot be divisible by 10, so N! There are M 0 at the end. Consider N again! Perform prime factor decomposition, N! = (2 ^ x) × (3 ^ y) × (5 ^ z )..., Since 10 = 2 × 5, M is only related to X and Z. Each pair of 2 and 5 can be multiplied to get a 10, so M = min (X, Z ). It is not hard to see that X is greater than or equal to Z, because the number of integers that can be divisible by 2 is much higher than the number that can be divisible by 5, so the formula is simplified to M = Z. The problem is equal to N! Contains the number of prime factor 5.
N! Contains the number of prime factor 5 Z = [N/5] + [N/5 ^ 2] + [N/5 ^ 3] +...
[Cpp]
Ret = 0;
For (I = 1; I <= N; I ++)
{
J = I;
While (j % 5 = 0)
{
Ret ++;
J/= 5;
}
}
 
Ret = 0;
While (N)
{
Ret + = N/5;
N/= 5;
}
N! In binary format. Given an integer N, evaluate N! Which of the following is the first digit of binary representation? For example, given N = 3, N! = 6, so N! The binary value of 110 indicates that the second digit is 1.
This problem is actually equivalent to finding N! Contains the number of prime factor 2. That is, the answer is equal to N! Add 1 to the number containing prime factor 2.
N! Contains the number of prime factor 2, equal to N/2 + N/4 + N/8 + N/16 +...
[Cpp]
Int lowestOne (int N)
{
Int Ret = 0;
While (N)
{
N> = 1;
Ret + = N;
}
Return Ret;
}


3. the array of N elements shifts K places to the right, and the time complexity is O (N)
[Cpp]
// O (n ^ 2) Algorithm
RightShift (int * arr, int N, int K)
{
K % = N;
While (K --)
{
Int t = arr [N-1];
For (int I = N-1; I> 0; I --)
Arr [I] = arr [I-1];
Arr [0] = t;
}
}
 
Void MoveCirce (int * data, int n, int m) // Recursive Implementation
{
Int temp = data [n-1];
For (int I = n-1; I> 0; -- I)
Data [I] = data [I-1];
Data [0] = temp;
M --;
If (m> 0)
MoveCirce (data, n, m );
}
Assume that the original array sequence is abcd1234 and the transformed array sequence is 1234 abcd, that is, four digits are shifted to the right of the loop. After comparison, it is not difficult to see that there are two segments in the same order: 1234 and abcd. we can regard these two segments as two parts. The K-bit shifting process is to swap the two parts of the array. Perform the following steps to complete the transformation:
1. Sort abcd in reverse order: abcd1234 → dcba1234;

2. Sort 1234 in reverse order: dcba1234 → dcba4321;

3. All reverse order: dcba4321 → 1234 abcd.

For pseudocode, refer to the following:
[Cpp]
Reverse (int * arr, int B, int e)
{
For (; B <e; B ++, e --)
{
Int temp = arr [e];
Arr [e] = arr [B];
Arr [B] = temp;
}
}
// Shift right of the loop
RightShift (int * arr, int N, int K)
{
K % = N;
Reverse (arr, 0, N-K-1 );
Reverse (arr, N-K, N-1 );
Reverse (arr, 0, N-1 );
}
// Move the loop left
LeftShift (int * arr, int N, int K)
{
K % = N;
Reverse (arr, 0, K-1 );
Reverse (arr, K, N-1 );
Reverse (arr, 0, N-1 );
}


4. maximum public approx.
Division: f (x, y) = f (y, x % y) (y> 0)
[Cpp]
Int gcd (int x, int y)
{
Return (! Y )? X: gcd (y, x % y );
}
Moving and subtraction: f (x, y) = f (x-y, y) (x> y)
[Cpp]
BigInt gcd (BigInt x, BigInt y)
{
If (x <y)
Return gcd (y, x );
If (y = 0)
Return x;
Else
Return gcd (x-y, y );
}
In the code, BigInt is a big integer class implemented by the reader (the so-called big integer can be hundreds of digits). Therefore, the reader is required to reload the subtraction operator "-" in the big integer class. the specific implementation of the big integer is not described here. If you just want to verify the correctness of the algorithm, you can use the built-in int type to test it.
[Cpp]
BigInt gcd (BigInt x, BigInt y)
{
If (x <y)
Return gcd (y, x );
If (y = 0)
Return x;
Else
{
If (IsEven (x ))
{
If (IsEven (y ))
Return (gcd (x> 1, y> 1) <1 );
Else
Return gcd (x> 1, y );
}
Else
{
If (IsEven (y ))
Return gcd (x, y> 1 );
Else
Return gcd (y, x-y );
}
}
}


5. Posting Mr. Shui: the number of "Shui Wang" posts exceeds half of the total number of posts
If an ID appears more than half of N. Then, no matter what the ID of the Water King is, the N/2 Item in the ordered id List (numbered from 0) must be this ID (readers can try to prove it ). This eliminates the need to scan the list again, saving you a little time spent on algorithms. If you can quickly locate an item in the list (such as using an array to store the list), in addition to the time complexity of sorting, the time required for post-processing is O (1 ).
If two different IDs are deleted each time (whether or not they contain the "Water King" ID), the number of occurrences of the "Water King" ID in the remaining ID list still exceeds half of the total number. After reading this, you can repeat this process to reduce the total number of IDs in the ID List (converted to a smaller question) to get the answer to the question. The new idea avoids the time-consuming steps of sorting. The total time complexity is only O (N), and only the extra memory of the constant is required. The pseudocode is as follows:
[Cpp]
Type Find (Type * ID, int N)
{
Type candidate;
Int nTimes, I;
For (I = nTimes = 0; I <N; I ++)
{
If (nTimes = 0)
{
Candidate = ID [I], nTimes = 1;
}
Else
{
If (candidate = ID [I])
NTimes ++;
Else
NTimes --;
}
}
Return candidate;
}
Expansion problem: the statistical results show that there are 3 posts with many IDs, and the number of posts exceeds 1/4 of the total number of posts N. Can you quickly find their IDs in the post ID list?
[Cpp]
Type candidate1;
Type candidate2;
Type candidate3;
 
Void Find (Type * ID, int N)
{
Int nTimes1 = 0;
Int nTimes2 = 0;
Int nTimes3 = 0;
Int I;
 
For (I = 0; I <N; I ++)
{
If (nTimes1 = 0)
{
Candidate1 = ID [I], nTimes1 = 1;
}
Else
{
If (candidate1 = ID [I])
{
NTimes1 ++;
}
Else
If (nTimes2 = 0)
{
Candidate2 = ID [I], nTimes2 = 1;
}
Else
{
If (candidate2 = ID [I])
{
NTimes2 ++;
}
Else
{
If (nTimes3 = 0)
{
Candidate3 = ID [I], nTimes3 = 1;
}
Else
If (candidate3 = ID [I])
{
NTimes3 ++;
}
Else
{
NTimes1 --;
NTimes2 --;
NTimes3 --;
}
}
}
}
}
}


6. Find the maximum K number
Finding the maximum K number in N is essentially the smallest K number, that is, the maximum K number. You can use the binary search policy to find the K-th largest number of N numbers. For a given number p, we can find all the numbers not less than p in the time complexity of O (N.
[Cpp]
// Find the k-th Element
Int select (int a [], int n, int k)
{
If (n <= 0 | k> n | k <= 0) return-1;
Int left = 0, right = n-1;
While (true)
{
Int j = rand () % (right-left + 1) + left;
Swap (a, j, left );
J = partition (a, left, right );
If (k = j + 1) return a [j];
Else if (k <j + 1) right = j;
Else left = j + 1;
}
}
If all N numbers are positive integers and their value ranges are not too large, you can apply for a space, record the number of occurrences of each integer, and then obtain the maximum K values from large to small. For example, if all integers are in the (0, MAXN) range, use an array count [MAXN] to record the number of occurrences of each INTEGER (count [I] indicates the number of occurrences of integer I among all integers ). You only need to scan it once to get the count array. Then, find the K-th element:
[Cpp]
For (sumCount = 0, v = MAXN-1; v> = 0; v --)
{
SumCount + = count [v];
If (sumCount> = K)
Break;
}
Return v;
In extreme cases, if N integers are different, we even need a bit to store whether the integer exists.


7. Quickly search for two numbers equal to a given number
Solution 1: Use the exhaustive method to retrieve any two numbers from the array and calculate whether the sum of the two is a given number. The time complexity is O (N ^ 2)
Solution 2: Assume that Sum is used. For each number in the array, arr [I] determines whether Sum-arr [I] is in the array, which becomes a search problem. To improve the search efficiency, first sort the search and then use the binary search method. The time complexity of the search is reduced from O (N) to O (logN ), the total time complexity is O (N * logN ).
Faster query method: hash table. For a given number, it is only required to query whether another number is in the Array Based on the hash ing, so that the total time complexity is reduced to O (N ), however, this requires additional O (N) hash table storage space.
Solution 3: first sort the array sort (a, n), the time complexity is O (N * logN), and then search by the following algorithm (the time complexity of O (N, the total time complexity is O (N * logN ).
[Cpp]
For (I = 0, j = n-1; I <j ;)
If (a [I] + a [j] = sum)
Return (I, j );
Else if (a [I] + a [j] <sum)
++ I;
Else
-- J;
Return (-1,-1 );


8. The longest incrementing subsequence in the array www.2cto.com
For example, in sequence 1,-7, the longest ascending sequence is 1, 2, 4, 6.
The problem is ineffective and can be solved through dynamic planning.
Among the first I elements of the target array a [], the maximum length of the ascending sub-sequence is LIS [I].
Then: LIS [I + 1] = max {1, LIS [k] + 1}, for any k <= I, a [I + 1]> a [k]
Dynamic Planning:
[Cpp]
Int LIS (int a [], int length)
{
Int LIS [] = new int [length];
For (int I = 0; I <length; ++ I)
{
LIS [I] = 1; // default initialization Length
For (int j = 0; j <I; ++ j) // The longest sequence above
If (a [I]> a [j] & LIS [j] + 1> LIS [I])
LIS [I] = LIS [j] + 1;
}
Return Max (LIS); // obtain the maximum value of LIS.
}
The time complexity of this method is O (N ^ 2 + N) = O (N ^ 2)

Author: luxiaoxun
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.