The answer to a Baidu pen question-general Linux technology-Linux programming and kernel information. The following is a detailed description. Implement a function and calculate the minimum number of operations required by 1 for a positive integer n:
If n is an even number, set it to 2;
If n is an odd number, you can add or subtract 1;
Keep processing.
Example:
Ret = func (7 );
Ret = 4, it can be proved that at least 4 operations are required
N = 7
N -- 6
N/2 3
N -- 2
N/2 1
Requirement: implement functions (as efficient as possible)
Int func (unsign int n); n is the input, and the minimum number of operations is returned.
Give the idea (text description), complete the code, and analyze the time complexity of your algorithm.
List test methods and ideas
A simple solution:
When n is written as binary, it is found that when 1 is less than 2 in a row, the "minus 1" method is used directly, with the minimum step; when 1 is more than 3 in a row, use the "Add 1" method, and then shift to the right, with the least steps. For a continuous 1 that is equal to 3, the steps minus 1 or adding 1 are the same.
Assume that the final processing result is 0 (not 1 of the question), then:
1) Each processing time is 0, a shift is used. A total of 1 step is required.
2) process consecutive d (d> = 3) values of 1, add 1 to it, and then move the d bit. A total of 1 + d steps are required.
3) Processing continuous d (0
4) because the question must be solved until the last 1 is left, the result must be corrected for a series of 1 s with the highest bit.
Int func (unsigned int n ){
Int d, ret = 0;
While (n ){
// 0 consecutive times
While (! (N & 0x01) n >>= 1, ret ++;
// Continuous 1
For (d = 0; n & 0x01 <d; d ++ );
If (d <3 ){
N> = d;
Ret + = d <1;
If (n = 0) ret --;
} Else {
N ++;
N> = d;
Ret + = 1 + d;
}
}
Ret --;
Return ret;
}
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.